feerlay
feerlay

Reputation: 2638

is async/await slower than promises?

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'

Upvotes: 5

Views: 2986

Answers (1)

Daniel Conde Marin
Daniel Conde Marin

Reputation: 7742

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

Upvotes: 7

Related Questions