为什么两者都承诺's然后&catch回调被调用

Why do both Promise's then & catch callbacks get called?

本文关键字:catch 调用 回调 amp 两者都 承诺 为什么 然后      更新时间:2023-09-26

我有以下代码,当它被执行时,它同时返回">rejected"answers">success":

// javascript promise
var promise = new Promise(function(resolve, reject){
  setTimeout(function(){reject()}, 1000)
});
promise
  .catch(function(){console.log('rejected')})
  .then(function(){console.log('success')});

有人能解释为什么会记录成功吗

调用then回调是因为catch回调在它之前,而不是之后。拒绝已由catch处理。如果更改顺序(即(promise.then(...).catch(...)((,则不会执行then回调。

MDN表示.catch()方法"返回一个解析回调返回值的新promise"。您的catch回调不返回任何内容,因此promise使用undefined值进行解析。

有人能解释为什么会记录成功吗?

简而言之:Promise链中.catch之后的.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(或也是.then.catch(可以对其进行操作。

可视化承诺链的流程

您可以通过以下示例可视化代码流:

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

对于那些成功解决了promise并订购了类似.then>.catch的链,但仍然调用了thencatch的人,这可能是因为您的then有一个抛出错误的错误,除非您显式地在catch中控制台该错误,否则您无法看到该错误。即使在严格模式下,Promises也会吸收错误,这是我最讨厌的事情之一。

const promise = new Promise(resolve => resolve())
.then(() => {
    console.log('then');
    not.defined = 'This causes the catch to fire even though the original promise resolved successfully.';
})
.catch((e) => {
    console.log('catch');
    // console.error(e);
});

对我来说,catch()是在成功承诺后调用的,.then()中没有错误。

原因是,我听取了一个随着成功承诺而变化的价值观,并运行了一种方法。

这个方法抛出了一个无声的错误,因为它被视为承诺的一部分。

类似于@Timar,对我来说,调用catch的原因是"那么";包含异常代码。所以在执行";那么";正常情况下,当它到达异常代码时,它在"中处理异常;捕获";xD