やりたいこと
setTimeout の実行後に、処理を実行したいとします。 ※ console.log の数字は実行したい順番を表しています。
console.log('1')
setTimeout(() => {
console.log('2')
}, 3000)
console.log('3')コンソールログ
1
3
2書いた順番通りには実行されません。
そこで Promise を使います。
resolve を使う
resolve() を呼んだタイミングで、thenブロックの中に入ります。
console.log('1')
new Promise((resolve) => {
setTimeout(() => {
console.log('2')
resolve()
}, 3000)
})
.then(() => {
console.log('3')
})コンソールログ
1
2
3reject を使う
reject() を呼んだタイミングで、catchブロックの中に入ります。
console.log('1')
new Promise((resolve, reject) => {
setTimeout(() => {
console.log('2')
try {
throw 'error!!!'
} catch (e) {
reject(e)
}
}, 3000)
})
.then(() => {
console.log('thenの中')
})
.catch((e) => {
console.log('catchの中', e)
})コンソールログ
1
2
catchの中 error!!!