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とかresolveとかthenとか

Last updated at Posted at 2023-10-28

同期処理とは?

上から順番に処理が実行される、いわゆる通常の処理。
前の処理が終わったら、次の処理が実行される。
前の処理が実行されないと次の処理が実行されない。

非同期処理とは?

上記の逆

処理の完了を待ってから次の処理へ進みたい。どうすればいい?

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

// NGパターン
console.log('1')

setTimeout(() => { // ただのsetTimeout関数が呼ばれているだけで、処理の完了を待って!って記述はない
    console.log('2')
}, 2000)

console.log('3')
// NGパターン
console.log('1')

new Promise(() => { // 非同期っぽく書いてるけどresolveを書いてないから処理が完了したタイミングが明示できない
    setTimeout(() => {
        console.log('2')
    }, 2000)  
}) // thenで繋げないと処理が完了した後に実行したい指示が明示できない

console.log('3')
// NGパターン
console.log('1')

new Promise((resolve, reject) => {
    setTimeout(() => {
        console.log('2')
        resolve()
    }, 2000)  
}) // resolveを書いてるけど、完了後に'3'を表示したいならthenで繋いで処理を記述しないと意図通りの動作はしない

console.log('3')
// OKパターン
console.log('1')

new Promise((resolve, reject) => {
    setTimeout(() => {
        console.log('2')
        resolve()
    }, 2000)  
}).then(() => {
    console.log('3')
})

処理の結果次第で出力する内容を変えたい。どうすればいい?

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

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

new Promise((resolve, reject) => {
    setTimeout(() => {
        if (result) {
            resolve('2') // resultがtrueだったらthenに繋いで、thenの引数には'2'が渡る
        } else {
            reject('10000') // resultがfalseだったらcatchに繋いで、catchの引数には'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?