谁能解释为什么记录成功?
简而言之:.catch 之后的 Promise 链中的 .then 将始终被执行(除非它本身包含错误)。
理论解释
您的代码实际上只是一个Promise 链,它首先同步执行,然后将其设置为异步完成。 Javascript 引擎会将任何reject() 或Error 传递给链中的第一个.then,其中包含reject 回调。拒绝回调是传递给 .then 的第二个函数:
.then(
function (){
//handle success
},
function () {
//handle reject() and Error
})
.catch 的使用只是语法糖:
.then(null, function () {
//handle reject() or Error
})
每个.then 都会自动返回一个新的Promise,后续.then (或.catch 也是.then 的)可以对其进行操作。
可视化承诺链的流程
您可以通过以下示例可视化您的代码流程:
var step1 = new Promise (function (resolve, reject) {
setTimeout(reject('error in step1'), 1000);
})
var step2 = step1.then(null, function () {
// do some error handling
return 'done handling errors'
})
var step3 = step2.then(function () {
// do some other stuff after error handling
return 'done doing other stuff'
}, null)
setTimeout (function () {
console.log ('step1: ', step1);
console.log ('step2: ', step2);
console.log ('step3: ', step3);
console.log();
console.log ('Asynchronous code completed')
console.log();
}, 2000);
console.log ('step1: ', step1);
console.log ('step2: ', step2);
console.log ('step3: ', step3);
console.log();
console.log ('Synchronous code completed')
console.log();
在运行时会在控制台中产生以下输出:
step1: Promise { <rejected> 'error in step1' }
step2: Promise { <pending> }
step3: Promise { <pending> }
Synchronous code completed
step1: Promise { <rejected> 'error in step1' }
step2: Promise { 'done handling errors' }
step3: Promise { 'done doing other stuff' }
Asynchronous code completed