简体   繁体   English

为什么Promise.reject()需要返回?

[英]Why does Promise.reject() require a return?

In the following code the Promise.reject doesn't work unless I specifically use return Promise.reject(...) . 在下面的代码Promise.reject没有工作,除非我专门使用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. Promise.reject创建一个值,它不会引发像throw那样从函数中断的异常。 If you don't return that value, it will be ignored and the control flow continues. 如果不return该值,它将被忽略并且控制流程继续。

Given you are inside a promise callback, you could (and possibly should) instead use 假设您位于promise回调中,则可以(可能应该)使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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