简体   繁体   中英

Rejecting a Promise with another new Promise

Im playing around with promises and i wanted a way of rejecting the promise inside of a then callback. So this is done by either calling throw return or return Promise.reject();. So far so good. You can accomplish this by also calling new Promise.reject(); withou a return.

Can someone explain why does this work?

new Promise((res, rej) => {
  setTimeout(() => {
    res(200);
  }, 2000);
})
  .then(() => {
    console.log("ok1");
    new Promise.reject();
    // return Promise.reject(); 
  .then(() => {
    console.log("ok2");
  })
  .catch(() => {
    console.log("error");
  });

 new Promise.reject()

Your code throws an exception. Exceptions cause promises to be rejected.

Because Promise.reject is not a constructor, this code works fine:

new Promise((res, rej) => {
  setTimeout(() => {
    res(200);
  }, 2000);
})
  .then(() => {
    console.log('ok1')
    Promise.reject('error!')
})
  .then(() => {
    console.log("ok2");
  })
  .catch(() => {
    console.log("error");
  });

New Promise.reject throws an error so the code jumps to the catch section with the following error: Promise.reject is not a constructor

 new Promise((resolve, reject) => { setTimeout(() => { resolve('OK'); }, 2000); }).then((res) => { console.log(res); new Promise.reject(); }).then((res) => { console.log(res); }).catch((err) => { console.log('error',err.message); });

That's because of the inner workings of Promise.reject . It basically does:

Promise.reject = function(err) {
  return new this((_, rej) => rej(err));
};

Now if you call it with new , this refers to a newly created object, and that's not a constructor.

 Promise.reject(); // this == Promise -> constructor
 new Promise.reject(); // this == {} -> not a constructor

Therefore, the .then callback throws an error, and that causes the returned Promise to be rejected with that error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM