4
async setMyPhotos() {
  const newPhotos = await Promise.all(newPhotoPromises);

  someOtherPromise();  // will wait for newPhotoPromises

  syncAvatar(newPhotos[0], function(res, err) {  // does this wait for newPhotoPromises too?
    if (!err) console.log("avatar sync'd");
  });

  return newPhotos;  // return just needs to wait for newPhotoPromises
}

I noticed syncAvatar seems to work, but I'm not sure if I'm just getting lucky or not. If so, how do I make sure syncAvatar only runs after newPhotoPromises are done?

To clarify, syncAvatar needs to happen after newPhotoPromises are done, however setMyPhotos just needs to return the results of newPhotoPromises, while syncAvatar can happen in the background.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
atkayla
  • 8,143
  • 17
  • 72
  • 132
  • async/await is C#? – jdmdevdotnet Jan 27 '17 at 17:40
  • 3
    JavaScript ES7 too! – atkayla Jan 27 '17 at 17:41
  • I was confused because the tag was only javascript :P – jdmdevdotnet Jan 27 '17 at 17:47
  • Of course `syncAvatar` will run after all the `newPhotoPromises` resolve. That's what `await` means. However, probably this code won't do what you want, especially if you intent to wait for `syncAvatar` to finish. –  Jan 27 '17 at 17:47
  • @torazaburo that is good to hear. I was under the impression that `await` is a `Promise` thing, so only `Promise` knows to `await`, but you're saying callbacks work too? I updated my post with a clarification that I do not intend to wait for `syncAvatar` to finish. I only intend for `syncAvatar` only run after `newPhotoPromises` are done. – atkayla Jan 27 '17 at 18:00
  • 2
    It's not that "callbacks work too". It's that execution pauses until the await is satisfied. Then, whatever comes next is executed. –  Jan 27 '17 at 18:05
  • 1
    `async/await` is *not* part of ES7 (ES2016). It *will* be part of this year's release, ES2017. – Felix Kling Jan 31 '17 at 15:49

1 Answers1

2

You say above that "async is a Promise thing". You're right. It is. It's basically syntactic sugar around promises to make them simpler to follow in certain contexts.

In this case, the function could actually be rewritten to look like this:

setMyPhotos() {
  return Promise.all(newPhotoPromises)
    .then(newPhotos => {
      someOtherPromise();

      syncAvatar(newPhotos[0], function(res, err) {
        if (!err) console.log("avatar sync'd");
      });

      return newPhotos;
    });
}

await basically tells the Javascript engine to wait for the Promise to be resolved before executing the rest of the function. Everything waits for the promise to be resolved: the function essentially pauses.

An async function in turn always returns a Promise, like the equivalent code above.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318