我的数组中有可变数量的数据。我想要一些东西来做到这一点:
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.any或https://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/