3
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.

async/await, Promiseの実行順序

Posted at

async/await, Promiseの実行順序はどうなるか気になったので調べてみました。

await.ts
const log = console.log;

async function f0() {
    return "ZZZ";
}
async function f1() {
    await f0();
    return "XXX";
}

log(1);
new Promise(async (resolve) => {
    resolve();
    log(2);
    await f0();
    // await f1();
    log(3);
}).then((value) => {
    log(4);
});
(async () => {
    log(5);
    await f0();
    // await f1();
    log(6);
})();
log(7);

実行結果は以下のとおり、await直前までの処理はすぐに行われるようです。

実行結果
1
2
5
7
3
4
6

下のコード内のawait f0()await f1()にぞれぞれ変えると
以下のとおり、then()の中身が先に実行されました。

実行結果
1
2
5
7
4
3
6
3
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
3
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?