为什么 Promise.reject() 需要 return?
Why does Promise.reject() require a return?
在下面的代码中,除非我专门使用 return Promise.reject(...)
,否则 Promise.reject
不起作用。这是为什么?
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
创建一个值,它不会像 throw
那样抛出从函数中断的异常。如果您不 return
该值,它将被忽略并且控制流继续。
鉴于您在 promise 回调中,您可以(并且可能应该)改用
throw new Error('Could not parse JSON');
在下面的代码中,除非我专门使用 return Promise.reject(...)
,否则 Promise.reject
不起作用。这是为什么?
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
创建一个值,它不会像 throw
那样抛出从函数中断的异常。如果您不 return
该值,它将被忽略并且控制流继续。
鉴于您在 promise 回调中,您可以(并且可能应该)改用
throw new Error('Could not parse JSON');