Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

またしても 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
willgate
ウィルゲートが理想とする社会は、一人ひとりが自身の『will(意志、想い、やりたいこと)』を実現できる社会です。
https://willgate.co.jp/
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした