最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - is asyncawait slower than promises? - Stack Overflow

programmeradmin1浏览0评论

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'

Share Improve this question asked Feb 25, 2018 at 21:03 feerlayfeerlay 2,6385 gold badges29 silver badges50 bronze badges 1
  • 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
Add a ment  | 

1 Answer 1

Reset to default 7

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.

发布评论

评论列表(0)

  1. 暂无评论