0
0

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.

動かして理解するasync/await

Posted at

JavaScriptのasync/awaitを動かしながら理解したい人向けです。
Node.jsで実行できます。

async/await
test()

// awaitを使う時はasyncが必要
async function test() {
    try {
        const code = await f(true)
        console.log(code)
        await f(false)
    } catch (err) {
        console.log(err)
    }
}

function f(ok) {
    // awaitする関数はPromiseを返す
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (ok) {
                // 正常終了
                resolve(200)
            } else {
                // 異常終了
                reject(500)
            }
        }, 3000)
    })
}

結果

200
500
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?