-4

In Javascript why we use async await while we have promise.all? I understand that because of chain of promises we use async await but we have promise.all there!? Really confused and stuck over here!

  • 1
    `Promise.all()` has no connection with `async...await`. Both are used in different scenarios. – msrumon Oct 24 '21 at 18:36
  • `Promise.all` is a mechanism to wait for multiple promises to resolve whereas `async/await` is a different syntax for handling promises – Nick Oct 24 '21 at 18:40

1 Answers1

0

async/await makes an asynchronous code look like a sequential code, therefore more readable.

Follows an example of asynchronous function that sums two values obtained asynchronously, written using Promise.all:

function sum () {
   return new Promise((resolve, reject) => {
       Promise.all([
           Promise.resolve(3),
           Promise.resolve(4)
       ]).then(values => {
           resolve(values[0] + values[1]);
       })
   })    
}

Now the same function written with async/await:

async function sum () {
    const a = await Promise.resolve(3);
    const b = await Promise.resolve(4);
    return a + b;
}

As you can see, the second function is much more readable and concise.