Why no-return-await vs const x = await?

后端 未结 3 1566
野趣味
野趣味 2020-12-29 02:29

What is the difference between

return await foo()

and

const t = await foo();
return t

http://eslint.org/d

3条回答
  •  温柔的废话
    2020-12-29 02:58

    Using return await does have some newly introduced benefits in v8 engine used by Node.js, Chrome and a few other browsers:

    v8 introduced a --async-stack-traces flag which as of V8 v7.3 is enabled by default (Node.js v12.0.0).

    This flags provides an improved developer experience by enriching the Error stack property with async function calls stack trace.

    async function foo() {
      return bar();
    }
    
    async function bar() {
      await Promise.resolve();
      throw new Error('BEEP BEEP');
    }
    
    foo().catch(error => console.log(error.stack));
    
    
    Error: BEEP BEEP
        at bar (:7:9)
    

    Note that by calling return bar(); foo() function call does not appear at all in the error stack. Changing it to return await bar(); gives a much better error stack output:

    async function foo() {
      return await bar();
    }
    
    Error: BEEP BEEP
        at bar (:7:9)
        at async foo (:2:10)
    

    This indeed does provide much better error stack tracing, hence it is HIGHLY encouraged to always await your promises.

    Additionally, async/wait now outperformes hand written promises:

    async/await outperforms hand-written promise code now. The key takeaway here is that we significantly reduced the overhead of async functions — not just in V8, but across all JavaScript engines, by patching the spec. Source

    Read more about these changes on the v8.dev blog: https://v8.dev/blog/fast-async#improved-developer-experience

提交回复
热议问题