繁体   English   中英

解决递归函数捕获中的承诺

[英]Resolve a promise from a recursive function catch

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

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拒绝产生未处理的承诺拒绝错误。 我认为在第一个函数调用中并没有像预期的那样捕获到拒绝。 如何调用第一个函数调用的拒绝? 还是应该在每个函数调用中将第一个承诺作为参数带给我?

这是promise构造函数的反模式 该构造的用于包装唯一遗产的API。

取而代之的是,始终如一地归还所有诺言,从而像应有的诺言那样束缚诺言。

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);
    })
  })
}

我刚刚找到了解决方案。 实际上,我应该已经定义了对返回的诺言的解决和拒绝,以便传递给上一个诺言:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM