Jeff的隨手筆記

學習當一個前端工程師

0%

用LeetCode寫日記-Day19

今天的題目很直覺的就是使用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 of promise should be an array of all the resolved values of promises in the same order as they were in the functions. The promise 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 promises
  • 1 <= functions.length <= 10

我的解題過程:

題目的要求是用非同步的方式去執行所有的array,如果有任何一個參數失敗就必須回傳第一個參數失敗的原因。

所以我們先設回傳的promise:

1
return new Promise((resolve, reject) => {})

在這個Promise裡面我會設定兩個變數,一個是儲存答案的array、一個是儲存成功執行的計數器。

1
2
const results = []
let complete = 0

接下來設定一個function 只要當我成功的次數=參數的數量時,我的回傳就會是results

1
2
3
4
5
const checkComplete = () => {
if (complete === functions.length) {
resolve(results)
}
}

最後就是讓所有的參數都遍歷一遍:

1
2
3
4
5
6
7
8
9
10
functions.forEach((func, index) => {
func().then((result) => {
results[index] = result
complete += 1
checkComplete()
})
.catch((error) => {
reject(error)
})
})

這樣就完成了

我的code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var promiseAll = function(functions) {
return new Promise((resolve, reject) => {
const results = []
let complete = 0

const checkComplete = () => {
if (complete === functions.length) {
resolve(results)
}
}

functions.forEach((func, index) => {
func().then((result) => {
results[index] = result
complete += 1
checkComplete()
})
.catch((error) => {
reject(error)
})
})
})

};

其他解法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var promiseAll = async function(functions) {
return await new Promise((resolve, reject) => {
// steps 1 and 2 of approach described above
let arr = Array(functions.length);
let waitingFor = functions.length;

// steps 3 and 4
for(let i = 0; i < functions.length; ++i){
functions[i]()
.then((result) => {
arr[i] = result;
if (--waitingFor === 0) resolve(arr);
}).catch(reject);
}
});
};

總結:

這題我覺得最困難的點就是如何讓當全部的參數的執行完後才去解析整個Promise,因此在想了一陣子後我用了一個function ,裡面放上一個判斷式,當滿足這個判斷式後,resolve才會得到我們的結果,