2017-10-06 35 views
0

我有一個數組中的數據的變量計數。我想要的東西,要做到這一點:我如何鏈接動態長度的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()函數在鏈中給出瞭解決方案,那麼跳轉到最後並用解析退出。

我知道,我的代碼是不正確的,這只是爲了表明我想要做什麼。

任何人都可以幫助我嗎?

謝謝!

+0

你爲什麼想用承諾這個? 'tryThis'不是異步函數。 – alexmac

+0

因爲tryThis()只是一個例子。我想稍後我們使用異步函數 而不是tryThis()。 – Scriba

回答

1

也許你可以使用藍鳥的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 
    }) 
+0

在此解決方案中運行tryThis()函數並列?因爲這對我不好。串聯運行所有功能非常重要,就像一個簡單的承諾鏈一樣。 我試試這個解決方案,但似乎不適合我。 – Scriba

0

所以,我的目標是創建一個無極鍊形成具有數據的變量計數和在所述端部鉤掛的陣列如果所有tryThis的()函數給出拒絕。如果其中一個tryThis()函數在鏈中給出瞭解決方案,那麼跳轉到最後並用解析退出。

隨着asyncawait

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

async function makeChain(arrayOfSomething: number[]): Promise<void> { 
    for (let num of arrayOfSomething) { 
    try { 
     await tryThis(num) // Call 'tryThis' sequentially 
     return    // The promise is resolved? Resolve the chain. 
    } catch (err) {  // The promise is rejected? Continue. 
    } 
    } 
    throw new Error("All the promises has been rejected") // Reject the chain. 
} 

let chain = makeChain([1, 2, 3, 4]) // 'chain' contains the promise