0
2

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 3 years have passed since last update.

JavaScript/TypeScript async関数を順番に実行したい

Posted at

非同期関数をそのまま実行した場合

コード

sleepで最初に実行した関数ほど遅く終了させます

const sleep = (time: number) => new Promise((resolve) => setTimeout(resolve, time));

const test = async (v: number) => {
  await sleep(100 - v * 10);
  console.log(v);
};

for (let i = 0; i < 10; i++) {
  test(i);
}

実行結果

当然のごとく、実行順序が入れ替わります

9
8
7
6
5
4
3
2
1
0

直列実行させた場合

コード

いろいろなやり方がありますが、ライブラリを使わない書き方でおそらく一番簡潔な方法です

const sleep = (time: number) => new Promise((resolve) => setTimeout(resolve, time));

const test = async (v: number) => {
  await sleep(100 - v * 10);
  console.log(v);
};

let p: Promise<void> | undefined;
for (let i = 0; i < 10; i++) {
  p = p?.then(() => test(i)) || test(i);
}

実行結果

次に実行する関数をPromise.thenで指定しているので、順番通りに実行されます

0
1
2
3
4
5
6
7
8
9
0
2
2

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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?