Page 134 - JavaScript
P. 134
iterating over the next one.
This is great if you actually want your somePromiseFn invocations to be executed in order but if you
want them to run concurrently, you will need to await on Promise.all.
(async() => {
data = [1, 2, 3, 4, 5];
const p = await Promise.all(data.map(async(e) => await somePromiseFn(e)));
console.log(...p);
})();
Promise.all receives an array of promises as its only parameter and returns a promise. When all of
the promises in the array are resolved, the returned promise is also resolved. We await on that
promise and when it's resolved all our values are available.
The above examples are fully runnable. The somePromiseFn function can be made as an async echo
function with a timeout. You can try out the examples in the babel-repl with at least the stage-3
preset and look at the output.
function somePromiseFn(n) {
return new Promise((res, rej) => {
setTimeout(() => res(n), 250);
});
}
Simultaneous async (parallel) operations
Often you will want to perform asynchronous operations in parallel. There is direct syntax that
supports this in the async/await proposal, but since await will wait for a promise, you can wrap
multiple promises together in Promise.all to wait for them:
// Not in parallel
async function getFriendPosts(user) {
friendIds = await db.get("friends", {user}, {id: 1});
friendPosts = [];
for (let id in friendIds) {
friendPosts = friendPosts.concat( await db.get("posts", {user: id}) );
}
// etc.
}
This will do each query to get each friend's posts serially, but they can be done simultaneously:
// In parallel
async function getFriendPosts(user) {
friendIds = await.db.get("friends", {user}, {id: 1});
friendPosts = await Promise.all( friendIds.map(id =>
db.get("posts", {user: id})
);
// etc.
}
https://riptutorial.com/ 91

