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 1 year has passed since last update.

Promiseとかasync,awaitとかtry,catch

Last updated at Posted at 2023-10-28

Promise/then か async/await か

  • 非同期処理で、処理を待ってから次のコードを実行したいのは同じ
  • 処理が完了を待ってから then を使って次の処理へ進むように記述するか、処理を完了を待っててほしい部分に await を使って記述するかの違い

ブラウザで試してみて

やりたいこと 1 ->(2秒後に)2 -> 3 の順番で表示させたい

  • Promise/then を使ったパターン
console.log('1')

new Promise((resolve, reject) => {
    setTimeout(() => {
        console.log('2')
        resolve()
    }, 2000)  
}).then(() => {
    console.log('3')
})
  • async/await を使ったパターン
console.log('1')

const show = async() => {
    await new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log('2')
            resolve()
        }, 2000)  
    })
    console.log('3')
}
show()

try/catch って何をやってるの?

  • 例外処理を記述したい時に使う
  • tryブロックで何かしらのエラーが起きた時、rejectが呼ばれた時にcatchブロックに進む

async/await を使う時に、try/catch を使う

やりたいこと 1 ->(2秒後に) resultの結果がtrueだったら 2, resultの結果がfalseだったら 10000, -> 3 の順番で表示させたい

const result = true
console.log('1')

const show = async() => {
    try { // tryブロック内で例外が発生したら(rejectが呼ばれたら)catchブロックへ進む
        const res = await new Promise((resolve, reject) => {
            setTimeout(() => {
                if (result) {
                    resolve('2') // 処理の返り値が'2'になる -> resに'2'が代入される
                } else {
                    reject('10000')
                }
            }, 2000)  
        })
        console.log(res) // resolveの返り値が'2'でresに'2'が代入されるためtryブロックが正常に動作したらlogに'2'が表示される
    } catch(e) {
        console.log(e) // rejectが呼ばれた場合は引数に値が渡ってくる
    } finally {
        console.log('3')
    }
}
show()
const result = true
console.log('1')

new Promise((resolve, reject) => {
    setTimeout(() => {
        if (result) {
            resolve('2')
        } else {
            reject('10000')
        }
    }, 2000)  
}).then(val => {
    console.log(val)
}).catch(e => {
    console.log(e)
}).finally(() => {
    console.log('3')
})
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?