Execution order of Promises in Node.js

两盒软妹~` 提交于 2021-01-07 03:16:15

问题


I executed following code with Node.js v10.15.0

Promise.resolve()
  .then(() => console.log('A'))
  .then(() => console.log('B'))
  .then(() => console.log('C'))

setImmediate(() => console.log('IMMEDIATE'))

Promise.resolve()
  .then(() => console.log('D'))
  .then(() => console.log('E'))
  .then(() => console.log('F'))

As there is no asynchronous code involved in the fullfilled functions i expected following output

A
B
C
D
E
F
IMMEDIATE

but i got...

A
D
B
E
C
F
IMMEDIATE

As far as i understand the situation, the setImmediate() call shows us, that none console.log() call gets deffered to the next Event Loop iteration. But, why is the order of console.log() calls mixed up?


回答1:


the setImmediate() call shows us, that no console.log() calls get deferred to the next Event Loop iteration

Actually they do - remember that promise then callbacks are always asynchronous.

They just do get run on a different phase of the event loop, they get queued on different task queues. For NodeJS specifically, see the article https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/ for details.

I expected following output

Don't assume anything about independent promise chains. All you can and should expect is that B comes after A, C comes after B, and in the other chain that E comes after D and F after E. They are allowed to be interleaved arbitrarily1 - if you want to ensure order, chain the promises to each other using then.

1: the spec details how the queuing of promise tasks works so that it is consistent between different engine implementations, but those details should be considered irrelevant.




回答2:


There are two Promise.resolve()... promise chains that are executed in parallel.

A
D
B
E
C
F

is the expected order for them.

In order to execute them in series, it should be:

Promise.resolve()
  .then(() => console.log('A'))
  .then(() => console.log('B'))
  .then(() => console.log('C'))
  .then(() => Promise.resolve()) // no-op
  .then(() => console.log('D'))
  .then(() => console.log('E'))
  .then(() => console.log('F'))


来源:https://stackoverflow.com/questions/54441138/execution-order-of-promises-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!