How does async / await work with callbacks in async functions?

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 that it syncAvatarseems to work, but I'm not sure if I'm just lucky or not. If so, how can I make sure it syncAvataronly works after completion newPhotoPromises?

To clarify, it syncAvatarshould happen after execution newPhotoPromises, however, setMyPhotosyou just need to return the results newPhotoPromises, whereas it syncAvatarcan happen in the background.

+4
source share
1 answer

You say above that " asyncis a Promisething." You're right. It. It is basically syntactic sugar around promises to make them easier in certain contexts.

:

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

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

      return newPhotos;
    });
}

await Javascript , Promise . , : .

async a Promise, .

+2

Source: https://habr.com/ru/post/1668032/


All Articles