Is using async/await slower in some scenarios than using promises?
Consider such code using promises
function foo() {
const p1 = new Promise(res => setTimeout(() => res('first'), 2000));
const p2 = new Promise(res => setTimeout(() => res('second'), 2000));
p1.then(console.log);
p2.then(console.log);
}
foo()
After 2000ms 'first'
and then 'second'
gets print out to the console.
The same code using async/await
async function foo() {
const p1 = await new Promise(res => setTimeout(() => res('first'), 2000));
const p2 = await new Promise(res => setTimeout(() => res('second'), 2000));
console.log(p1);
console.log(p2);
}
foo();
with async/await it takes 4000ms to print 'first'
and 'second'
Is using async/await slower in some scenarios than using promises?
Consider such code using promises
function foo() {
const p1 = new Promise(res => setTimeout(() => res('first'), 2000));
const p2 = new Promise(res => setTimeout(() => res('second'), 2000));
p1.then(console.log);
p2.then(console.log);
}
foo()
After 2000ms 'first'
and then 'second'
gets print out to the console.
The same code using async/await
async function foo() {
const p1 = await new Promise(res => setTimeout(() => res('first'), 2000));
const p2 = await new Promise(res => setTimeout(() => res('second'), 2000));
console.log(p1);
console.log(p2);
}
foo();
with async/await it takes 4000ms to print 'first'
and 'second'
- 4 It is not the same code. The first snippet runs two promises in parallel when the second one does it sequentially. Async / await cannot be slower than promises because it is based on promises, they are just the same – smnbbrv Commented Feb 25, 2018 at 21:05
1 Answer
Reset to default 7Your equivalent of the first snippet in async / await
is wrong, should be:
async function foo() {
const p1 = new Promise(res => setTimeout(() => res('first'), 2000));
const p2 = new Promise(res => setTimeout(() => res('second'), 2000));
const result = await Promise.all([p1,p2]);
console.log(result[0]);
console.log(result[1]);
}
foo();
The first snippet you have runs the promises concurrently, the second synchronously. That's why await
should be used with good care and knowledge.
CAVEAT
As pointed by @Bergi, bear in mind Promise.all
is all or nothing, so if one promise fails it will reject immediately, which is not the case in your first snippet.