我有一個數組中的數據的變量計數。我想要的東西,要做到這一點:我如何鏈接動態長度的Promise函數?
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
})
所以,我的目標是創建一個無極鍊形成數據的變盤點,並在年底趕上一個數組,如果所有tryThis()函數給出了拒絕。如果其中一個tryThis()函數在鏈中給出瞭解決方案,那麼跳轉到最後並用解析退出。
我知道,我的代碼是不正確的,這只是爲了表明我想要做什麼。
任何人都可以幫助我嗎?
謝謝!
你爲什麼想用承諾這個? 'tryThis'不是異步函數。 – alexmac
因爲tryThis()只是一個例子。我想稍後我們使用異步函數 而不是tryThis()。 – Scriba