如何将动态长度的Promise函数链接起来?

时间:2017-10-06 12:17:08

标签: javascript node.js typescript

我在数组中有可变数据。我想要一些东西,这样做:

function tryThis(num: number): Promise<any> {
  return new Promise ((resolve, reject) => {
    if(num == 3){
      resolve()
    }else{
      reject();
    }
  }
}

let arrayOfSomething : Array<number> = [1,2,3,4];
let chain;

// create the chain
arrayOfSomething.forEach( (element) => {
    // add element to the chain
    chain.catch(() => {
      tryThis(element);
    });
});


// run chain
chain
  .then(() => {
    // one of elemnts of the array was 3
  })
  .catch(() => {
    // no "3" found in array
  })

所以,我的目标是创建一个Promise链,形成一个具有可变数据计数的数组,并在最后捕获,如果所有tryThis()函数都给出拒绝。如果tryThis()函数中的一个在链中给出了解析,则跳转到最后并以解决方式退出。

我知道,我的代码不正确,这只是为了展示我想要做的事情。

任何人都可以帮助我吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

也许您可以使用bluebird中的Promise.any或其他库中的类似功能:https://www.npmjs.com/package/promise.anyhttps://www.npmjs.com/package/promise-any

如果拒绝所有元素,则

Promise.any被拒绝。因此,您需要从数组中创建承诺数组,然后调用Promise.any。例如:

let arrayOfSomething = [1,2,3,4];
Promise.any(arrayOfSomething.map(x => tryThis(x))
  .then(() => {
    // one of elemnts of the array was 3
  })
  .catch(() => {
    // no "3" found in array
  })
相关问题