Value of Promise.all() after it is rejected, shows [''PromiseStatus'']: resolved if catch block is present

后端 未结 2 514
醉梦人生
醉梦人生 2021-01-18 18:12

I have two promises, one rejected and other resolved. Promise.all is called. It executed the catch block of Promise.all as one of the promises is rejected.

c         


        
2条回答
  •  逝去的感伤
    2021-01-18 18:55

    A catch on a Promise acts the same as a try {} catch {} block, in that you have captured the error state and the program will continue to function as normal.

    That's why, when you omit the catch, your promise state is "rejected".

    If, after having caught the error, you want to return the promise state as rejected you need to return a rejected promise from the catch handler:

    const promise3 = Promise.all([promise1, promise2])
        .catch(error => {
            console.log("REJECTED", error);
            return Promise.reject(error);
        });
    console.log(promise3); // [[PromiseStatus]]: "rejected"
    

    Similar to doing a throw inside a try {} catch { throw; } block

提交回复
热议问题