我是 Promises 新手,在尝试 .then 方法时遇到了意外行为。下面的 Promise 被拒绝,并且 .then 方法中的函数返回了一个值,但 Promise 显示 {: '{Error gone Here'} 并且 console.log 似乎没有被执行。
var myPromise = new Promise((res,rej)=>{
rej("Error goes here")
})
.then(function(a){},
function(error) {
console.log('then called', error)
return error;
})
//Returns "{<fulfilled>: 'Error goes here'}"
为什么显示为“fulfilled”并且console.log未执行?
.then() 的第二个参数是拒绝处理程序。当初始承诺被拒绝时,将调用拒绝处理程序,该处理程序会记录消息并返回错误。因为您从拒绝处理程序返回一个值,所以该承诺被视为已使用该值解决。这就是为什么您看到承诺“已履行”并且 console.log 已执行。
如果您想维持 Promise 的拒绝状态并仍然记录错误,您应该从 .then() 调用中删除拒绝处理程序并使用单独的 .catch() 块来处理错误:
var myPromise = new Promise((res, rej) => {
rej("Error goes here");
})
.then(
function(a) {},
function(error) {
// This code won't be executed if the promise is rejected
}
)
.catch(function(error) {
console.log('catch called', error);
});