Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
14
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

@okashoi

Promise で resolve/reject が呼ばれても処理は中断しない

またしても Promise まわりの勘違いにより、どハマリしたので書いておく。

resolve()reject() が呼ばれただけでは処理は中断しない

new Promise((resolve, reject) => {
    console.log('before');
    resolve();
    console.log('after');
})
    .then(() => console.log('then'))
    .catch(() => console.log('catch'));

実行結果
before
after
then

new Promise((resolve, reject) => {
    console.log('before');
    reject();
    console.log('after');
})
    .then(() => console.log('then'))
    .catch(() => console.log('catch'));

実行結果
before
after
catch

どちらの例もバッチリ console.log('after') が実行されている。

対策

resolve() / reject() の呼び出しと一緒に return しておく。

new Promise((resolve, reject) => {
    console.log('before');
    return resolve();
    console.log('after');
})
    .then(() => console.log('then'))
    .catch(() => console.log('catch'));

実行結果
before
then

これで console.log('after') は実行されない。

【余談】resolve()reject() を両方呼ぶとどうなるか

new Promise((resolve, reject) => {
    console.log('before');
    resolve();
    reject();
    console.log('after');
})
    .then(() => console.log('then'))
    .catch(() => console.log('catch'));

答えは先に呼ばれたもの勝ち。

後から呼ばれた reject()catch() の処理は実行されない。

実行結果
before
after
then
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
14
Help us understand the problem. What are the problem?