【问题标题】:Resolve a promise from a recursive function catch从递归函数 catch 中解决一个 Promise
【发布时间】:2017-09-09 08:32:11
【问题描述】:

我有一个函数在捕获错误时使用不同的输入递归调用自身:

function getSomething(inputs, index) {

  var index = index || 0
    , indexMax = inputs.length - 1

  return new Promise((resolve, reject) => {
    //inputs[index].staff is an array and getSomethingElse returns a Promise
    Promise.all(inputs[index].staff.map(getSomethingElse))
    .then(output => {
      resolve(output)
    })
    .catch(reason => {
      if(index<indexMax)
        getSomething(inputs, index+1);
      else
        reject(reason);
    })
  })
}

getSomething(myInputs)
.then(output => {
  console.log('resolved with this:'+output);
})
.catch(reason => {
  console.log('rejected because of this:'+reason);
});

我收到 UnhandledPromiseRejectionWarning: 来自 getSomethingElse 拒绝的未处理的承诺拒绝错误。我认为这种拒绝没有像预期的那样在第一个函数调用中被捕获。如何调用第一个函数调用的拒绝?还是我应该在每个函数调用中带上第一个承诺作为参数?

【问题讨论】:

  • 试试return getSomething(inputs, index + 1)
  • 我刚试过,结果一样..

标签: javascript recursion promise es6-promise


【解决方案1】:

这是promise constructor anti-pattern。构造函数仅用于包装旧版 API

取而代之的是,像始终 returning all of them 那样链接承诺。

function getSomething(inputs, index = 0) {
  return Promise.all(inputs[index].staff.map(getSomethingElse))
    .catch(reason => {
      if (index >= inputs.length - 1) throw reason;
      return getSomething(inputs, index+1);
    })
  })
}

【讨论】:

    【解决方案2】:

    我刚刚找到了解决方案。事实上,我应该从返回的 Promise 中定义 resolve 和 reject,以便传输到前一个:

     if(index<indexMax) {
       getSomething(inputs, index+1)
       .then(output => {
         resolve(output);
       })
       .catch(reason => {
          reject(reason);
       })
    }
     else
       reject(reason);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      • 2023-03-31
      • 1970-01-01
      • 2022-11-29
      • 1970-01-01
      相关资源
      最近更新 更多