2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

node.jsにおける非同期処理の順序

Last updated at Posted at 2019-10-01

node.jsには、現在の処理を抜けた後に、即時実行するためのコマンドが4つある。

  • setImmediate(f)
  • setTimeout(f,0)
  • process.nextTick(f)
  • Promise.resolve().then(f)

どの順序で実行されるか、調べた結果をまとめておく。

先に結論を述べると、以下の順序になっている。(左が先に実行される)
process.nextTick(f) > Promise.resolve().then(f) > setTimeout(f,0) ≒ setImmediate(f)

この順序で実行されることは、以下のページで説明されている。
https://nodejs.dev/

コードで確認

実際にコードを書いて試してみる。

main.js
setImmediate(() => {
  console.log('setImmediate')
})
setTimeout(() => {
  console.log('setTimeout0')
}, 0)
Promise.resolve().then(() => {
  console.log('Promise Job')
})
process.nextTick(() => {
  console.log('nextTick')
})
console.log('main')
実行結果
$ node main.js
main
nextTick
Promise Job
setTimeout0
setImmediate

setTimout(f,0)とsetImmediate(f)については、試した環境では常にsetTimeout(f,0)が先だったが、
説明によると確定ではないようである。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?