JS Promise's inconsistent execution order between nodejs versions

前端 未结 1 1926
隐瞒了意图╮
隐瞒了意图╮ 2021-01-06 04:33

I am reading the article about nodejs promise here.

Then I try running the following sample code (from the article)

const p = Promise.resolve();

(asyn         


        
相关标签:
1条回答
  • 2021-01-06 05:15

    This is due to this change in the specs which now allows shortcircuiting await promiseInstance to not wrap promiseInstance into a new Promise internally and hence saving two ticks (one for waiting for promiseInstance and one to wake up the async function).

    Here is a detailed article from the authors of the specs' patch, which also occur to be v8 devs. In there, they explain how that behavior was actually already in nodejs v.8 but was against the specs by then, i.e a bug, that they fixed in v.10, before this patch makes it the official way of doing, and it gets implemented in v8 engine directly.

    So if you wish the inlined version that should have happened before this patch is

    const p = Promise.resolve();
    
    new Promise((res) => p.then(res)) // wait for p to resolve
      .then((res) => Promise.resolve(res)) // wake up the function
      .then((res) => console.log('after:await'));
    
    p.then(() => console.log('tick:a'))
     .then(() => console.log('tick:b'));
    

    while the patch makes it

    const p = Promise.resolve();
    
    p.then(() => console.log('after:await'));
    
    p.then(() => console.log('tick:a'))
     .then(() => console.log('tick:b'));
    
    0 讨论(0)
提交回复
热议问题