0

I'm using async/await in a for loop to wait for a get method which have an observable inside.. So I wrap it in a promise which is resolve when the observable receive data and then it unsubscribe using a take(1) operator..

async addImgStorage(postId, base64data) {
    let urls = [];
    for (let i = 0; i < base64data.length; i++) {
      const file = "data:image/jpg;base64," + base64data;
      const filePath = "img/" + postId + "_" + i;
      let url = await this.getUrl(filePath, file);
      urls.push(url);
    }
    this.addImagen(postId, urls);
  }

 getUrl(filePath, file) {
    return new Promise((resolve, reject) => {
      const ref = this.storage.ref(filePath);
      ref.putString(file, "data_url").then(() => {
        const downloadURL = ref
          .getDownloadURL()
          .pipe(take(1))
          .subscribe(url => {
            if (url) {
              resolve(url);
              console.log("url from get", url);
            }
          });
      });
    });
  }

 addImagen(postId, urls) {
    const imagen: Imagen = {
      postId: postId,
      img: { ...urls }
    };
    this.afDB.list("imagenes").push(imagen);
  }

the above code works fine if base64data's length is 1 but throw the following error when its length > 1

ERROR Error: Uncaught (in promise): [object Object]

poimsm2
  • 512
  • 1
  • 7
  • 23
  • Solved: I just forgot to add the index in the base64data when assigning file constant.. so I was passing the whole array in the query... – poimsm2 Aug 26 '18 at 06:40
  • an alternative if you wish to go for a different approach. https://stackoverflow.com/questions/28983424/make-angular-foreach-wait-for-promise-after-going-to-next-object – Yushin Aug 26 '18 at 13:07

0 Answers0