DEV Community

Discussion on: JavaScript: Promises and Why Async/Await Wins the Battle

Collapse
 
kepta profile image
Kushan Joshi • Edited

Nick this is a great article, but there are some problems (as others have pointed too) with the way you interpret Async/Await as the next evolution of Promises.

You can call Promises as the next evolution of the callback code, but the Async/Await is not exactly an evolution. It is meant to supplement Promises and not replace it. For example you can use a combination of Promises and Await to get a much more readable code than flooding you code with awaits.

In your example

async function foo() {
        response[0] = await axios.get(`/users/userId=${users[0]}`);
        response[1] =  await axios.get(`/users/userId=${users[1]}`);
        response[2] = await axios.get(`/users/userId=${users[2]}`);
       // do the thing
}

Async/Await heavy codes like the one above, encounter a problem of running out of variable names (you have used an array, which is clever but doesn't really improve readability)

This code can be improved by doing something by

async function() {
        response =  await Promise.all([1,2,3].map(i => axios.get(`/users/userId=${i}`));
       // do the thing
}

In a lot of cases you really want to pipe a bunch of results to multiple async calls, for this again promises work like a charm:

async function foo() {
   const final = await axios.get(`/users/userId=${users[0]}`)
  .then(r => processUser(r))
  .then(r => getUserData(r))
}