DEV Community

Niklas
Niklas

Posted on • Originally published at niklasmtj.de

Simultaneous Promises with async/await

I recently got me a membership of egghead.io (this is a referral code) to learn more about web development and all those new technologies. I watched a quick course about async / await and did some notes. These are the ones about sending parallel promises and awaiting them afterwards.

Sending multiple promises at the same time

async displayDevicesAndUsers() => {

    // Since both promises are stored in variables,
    // they are fetched in parallel from the api
    const devicesPromise = fetchApi("devices"); 
    const usersPromise = fetchApi("users");


    // The results can then be extracted with await
    const devices = await devicesPromise;   
    const user = await userPromise; 
} 

Promise.all

There is also an easier method. You can use Promise.all. This will create one promise, that will reserve when all promises in it’s array resolved. The promise will be rejected when one of the promises inside fails. I will use the previous example and refactor it with Promise.all

async displayDevicesAndUsers() => {

    // 1st option to retrieve results
    const results = Promise.all([
        fetchApi("devices");
        fetchApi("users");
    ]);
    const devices = results[0];
    const users = results[1];

    // 2nd option, which is a little shorter
    // and uses ES2015 array destructuring 
    const [devices, users] = Promise.all([
        fetchFromGitHub("devices");
        fetchFromGitHub("users");
    ]);
}

Top comments (0)