javascript - 如何使用动态长度链接 Promise 函数?

标签 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() 函数之一在链中给出了解析,则跳转到末尾并以解析退出。

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

任何人都可以帮助我做到这一点吗?

谢谢!

最佳答案

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

如果所有元素都被拒绝,

Promise.any 将被拒绝。因此,您需要从数字数组中创建 Promise 数组,然后调用 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
  })

关于javascript - 如何使用动态长度链接 Promise 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46605562/

相关文章:

c# - 页面渲染和 http 处理程序

javascript - 使用 node.js 连接到已经建立的 UNIX 套接字?

node.js HTTPs 调用返回未定义。亚马逊AWS

javascript - 按属性名称从另一个数组中选取数组

angular - Angular2 typescript 中的第三方 JS

javascript - 向 Vue.js 组件添加数据

javascript - angularjs $location 和 window.history.pushState

sockets - 如何获得在 Nodejs 应用程序上使用 socket.io 的性能基准

node.js - 如何使用 yarn 执行 bin?

javascript - 为数组中的每个元素创建 html 元素( Angular )