【问题标题】:Error propagation in chained Promise not working as expected链式 Promise 中的错误传播未按预期工作
【发布时间】:2019-04-13 01:56:33
【问题描述】:

我正在从this site. 学习 JS Promises 中的链接基于高级示例,我编写了以下代码以更好地理解错误传播。

var promise = new Promise((resolve, reject) => {
    reject('Rejected!');
});

promise.then(()=>new Promise ((resolve, reject) => resolve('Done!')), () => console.log('Failure of first Promise'))
       .then(() => console.log('Success of nested Promise'), () => console.log('Failure of nested Promise'));

console.log('This will be still printed first!');

在这里,当我拒绝第一个承诺时,它正在记录 Failure of first Promise,然后是 Success of nested Promise

现在我想知道嵌套 Promise 的成功回调是怎么回事?正如上面提到的文章中所解释的,很明显,即使一个 promise 失败(rejected),也应该调用失败回调。

我在这里缺少什么?谢谢。

【问题讨论】:

  • 如果错误需要向下传播error => throw error;,请重新抛出错误,或者如果您需要更改某些错误对象属性,则在拒绝处理程序中抛出新错误。 error => throw new Error( 'some other error description' );.

标签: javascript node.js ecmascript-6 promise es6-promise


【解决方案1】:

第二个then 回调从前一个promise 中捕获错误(在try..catch 中捕获)。 在这种特定情况下(第一个 then 回调不可能导致拒绝)这与:

promise // rejected promise
.then(()=>new Promise ((resolve, reject) => resolve('Done!'))) // skips rejected promise
.catch(() => console.log('Failure of first Promise')) // results in resolved promise
.then(() => console.log('Success of nested Promise')) // chains resolved promise
.catch(() => console.log('Failure of nested Promise')); // skips resolved promise

【讨论】:

    【解决方案2】:

    你写的代码是这样的

    var promise = new Promise((resolve, reject) => { reject('Rejected!'); });
    promise
        .then(()=>new Promise ((resolve, reject) => resolve('Done!')))
        .catch(() => console.log('Failure of first Promise'))
        .then(() => console.log('Success of nested Promise'))
        .catch(() => console.log('Failure of nested Promise')); 
        console.log('This will be still printed first!');
    

    由于catch 也返回一个promise,与catch 链接的then 也将被触发,如果在所有then 的末尾只有一个catch,则该catch 将在没有任何@ 的情况下触发987654327@.

    您可以执行以下操作来解决此问题,

    promise
        .then(()=>new Promise ((resolve, reject) => resolve('Done!')))
        .then(() => console.log('Success of nested Promise'))
        .catch(() => console.log('Failure of Promise')); 
        console.log('This will be still printed first!');
    

    【讨论】:

      【解决方案3】:

      这是因为

      catch() 方法返回一个 Promises

      MDN source - Promise.prototype.catch()

      "use strict";
      
      new Promise((resolve, reject) => {
        reject('Error');
      }).catch(err => {
        console.log(`Failed because of ${err}`);
      }).then(() => {
        console.log('This will be called since the promise returned by catch() is resolved');
      });
      

      这将记录

      因错误而失败
      由于 catch() 返回的承诺已解决,这将被调用

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-25
        • 1970-01-01
        • 1970-01-01
        • 2014-12-03
        • 1970-01-01
        • 2014-01-09
        • 2021-08-04
        相关资源
        最近更新 更多