Skip to content

Instantly share code, notes, and snippets.

@genya0407
Last active August 19, 2019 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save genya0407/7b66e088102e2014cf672421422e0bb5 to your computer and use it in GitHub Desktop.
Save genya0407/7b66e088102e2014cf672421422e0bb5 to your computer and use it in GitHub Desktop.
awaitが止めるのはラインタイムではなくasync関数
// await演算子が一時停止するのは「async関数の実行」であって「ランタイムの実行」ではない、ということを実験的に示す。
//
// 侍エンジニア塾の記事のミスリーディングな記述(↓)に対する補足
// https://www.sejuku.net/blog/69618
// > 「await」はPromise処理の結果が返ってくるまで一時停止してくれる演算子となります
// 1秒待つだけのPromiseを返す関数を定義する
const oneSecond = () => new Promise(resolve => setTimeout(resolve, 1000))
// 1秒ごとに "a: n seconds"と表示するasync関数を定義する
const asyncFuncA = async () => {
await oneSecond();
console.log("a: 1 seconds")
await oneSecond();
console.log("a: 2 seconds")
await oneSecond();
console.log("a: 3 seconds")
}
// 1秒ごとに "b: n seconds"と表示するasync関数を定義する
const asyncFuncB = async () => {
await oneSecond();
console.log("b: 1 seconds")
await oneSecond();
console.log("b: 2 seconds")
await oneSecond();
console.log("b: 3 seconds")
}
// これら2つのasync関数を実行する
asyncFuncA();
asyncFuncB();
// asyncFuncAとasyncFuncBはasync関数なので、瞬時にここまで来る
console.log('Start printing')
// この後に "a: n seconds"とかが表示される
// 仮にawaitが、Promiseの結果が返ってくるまで「JavaScriptのランタイムを」一時停止するのであれば、表示は以下のようになるはず:
//
// Start printing
// a: 1 seconds
// a: 2 seconds
// a: 3 seconds
// b: 1 seconds
// b: 2 seconds
// b: 3 seconds
//
// もしくは
//
// Start printing
// b: 1 seconds
// b: 2 seconds
// b: 3 seconds
// a: 1 seconds
// a: 2 seconds
// a: 3 seconds
//
// つまりasyncFuncAが全部実行された後にasyncFuncBの実行が始まる(もしくはその逆)、ということ。
//
// しかし実際の表示は以下のようになる:
//
// Start printing
// a: 1 seconds
// b: 1 seconds
// a: 2 seconds
// b: 2 seconds
// a: 3 seconds
// b: 3 seconds
//
// これが意味するのは、awaitが一時停止するのは「async関数」であって、「JavaScriptのランタイム」ではない、ということ。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment