Simultaneous async parallel operations

suggest change

Often you will want to perform asynchronous operations in parallel. await waits for one promise. Wrap several promises in Promise.all to wait for all of them. The snippets below treat friendIds as an array of ids.

// Not in parallel

async function getFriendPosts(user) {
    const friendIds = await db.get("friends", {user}, {id: 1});
    let friendPosts = [];
    for (const id of friendIds) {
        friendPosts = friendPosts.concat(await db.get("posts", {user: id}));
    }
    // etc.
}

This runs each posts query one after another. The queries can run at the same time:

// In parallel

async function getFriendPosts(user) {
    const friendIds = await db.get("friends", {user}, {id: 1});
    const friendPosts = await Promise.all(friendIds.map(id =>
      db.get("posts", {user: id})
    ));
    // etc.
}

map builds an array of promises. Promise.all settles when every promise has settled, and those requests are in flight together. It rejects if any of them rejects.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents