Reputation: 8849
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.
Upvotes: 4
Views: 807
Reputation: 237865
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.
Upvotes: 2