简体   繁体   中英

Why does Promise.reject() require a return?

In the following code the Promise.reject doesn't work unless I specifically use return Promise.reject(...) . Why is this?

Promise.resolve('Promise 1 Done')
.then(function(result) {
  console.log(result);
  return 'Promise 2 Done'
}).then(function(result) {
  let j;
  try {
    j = JSON.parse("invalid will throw");
    console.log(j);
  } catch(err) {
    Promise.reject('Could not parse JSON');
  }

  console.log(result);
}).catch(function(err) {
  console.log(err);
});

Promise.reject creates a value, it does not throw an exception that breaks from the function like throw does. If you don't return that value, it will be ignored and the control flow continues.

Given you are inside a promise callback, you could (and possibly should) instead use

throw new Error('Could not parse JSON');

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