-1

Im a bit struggling to grasp promises, I have a use case when I perform X async actions, and when these are completed I make call to rest api. below my code:

const promises = defect.images.map(async image => {
      return new Promise((resolve)=> {
        this.fileProvider.getDefectImage(image.url)
          .then(binary => {
            images.set(image.url, binary);
            resolve();
          });
      })
    });
    console.log(images)
    return Promise.all(promises)
      .then(() => spinner.dismiss())

but the console.log of images is always empty ... what should i change?

//edit sorry guys for leading into a trap, indeed this console.log can not work properly but Im not getting the data on bakcend side, its also empty there.

filemonczyk
  • 1,613
  • 5
  • 26
  • 47
  • `console.log` after the Promise returned by Promise.all has resolved. Like this: `.then( () => { console.log(images); return spinner.dismiss(); } )` – Paul Nov 06 '18 at 16:12
  • Why `new Promise()` when `this.fileProvider.getDefectImage()` already returns a Promise? – Andreas Nov 06 '18 at 16:12
  • ^^ and since it does, there's no reason for making the `map` callback `async`. You *already* have a promise, no need to use the syntax to create one for you. – T.J. Crowder Nov 06 '18 at 16:13
  • FWIW: https://pastebin.com/hX7qkdAK (see comments), if you're using promises explicitly (not `async` functions). If using an `async` function: https://pastebin.com/0zc2kYbx – T.J. Crowder Nov 06 '18 at 16:18

1 Answers1

0

You are logging images before any of the promises have been resolved, so it's still empty at that point.

You need to wait for all the promises to be resolved first. And apparently you already know how to do that:

return Promise.all(promises)
  .then(() => {
    console.log(images);
    spinner.dismiss();
  })

Besides, you are mixing async/await syntax and Promise syntax. If you're going to rely on async/await, you might as well go all the way, and then your code will be executed from top to bottom again:

const promises = defect.images.map(async image => {
  let binary = await this.fileProvider.getDefectImage(image.url);
  images.set(image.url, binary);
});
await Promise.all(promises);
console.log(images);
spinner.dismiss();
Thomas
  • 174,939
  • 50
  • 355
  • 478