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!
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.