今天的題目很直覺的就是使用Promise,基本上沒有太奇怪或是不懂的地方。
Day19: Execute Asynchronous Functions in Parallel
問題描述:
Given an array of asynchronous functions functions
, return a new promise promise
. Each function in the array accepts no arguments and returns a promise. All the promises should be executed in parallel.
promise
resolves:
- When all the promises returned from
functions
were resolved successfully in parallel. The resolved value ofpromise
should be an array of all the resolved values of promises in the same order as they were in thefunctions
. Thepromise
should resolve when all the asynchronous functions in the array have completed execution in parallel.
promise
rejects:
- When any of the promises returned from
functions
were rejected.promise
should also reject with the reason of the first rejection.
Please solve it without using the built-in Promise.all
function.
問題難度:Medium
問題限制:
functions
is an array of functions that returns promises1 <= functions.length <= 10
我的解題過程:
題目的要求是用非同步的方式去執行所有的array,如果有任何一個參數失敗就必須回傳第一個參數失敗的原因。
所以我們先設回傳的promise:
1 | return new Promise((resolve, reject) => {}) |
在這個Promise裡面我會設定兩個變數,一個是儲存答案的array、一個是儲存成功執行的計數器。
1 | const results = [] |
接下來設定一個function 只要當我成功的次數=參數的數量時,我的回傳就會是results
1 | const checkComplete = () => { |
最後就是讓所有的參數都遍歷一遍:
1 | functions.forEach((func, index) => { |
這樣就完成了
我的code:
1 | var promiseAll = function(functions) { |
其他解法:
1 | var promiseAll = async function(functions) { |
總結:
這題我覺得最困難的點就是如何讓當全部的參數的執行完後才去解析整個Promise,因此在想了一陣子後我用了一個function ,裡面放上一個判斷式,當滿足這個判斷式後,resolve
才會得到我們的結果,