Given an array of asynchronous functions functions, where each function in the array takes no arguments and returns a Promise, and all Promises in the array should be executed concurrently. The function ultimately returns a promise.
The resolving condition of the promise:
functions are successfully resolved concurrently, the promise returned by the function will resolve. The resolved value of the promise should be an array containing the resolved values in the same order as in functions. The promise is resolved only when all asynchronous functions in the array are executed concurrently.The rejection scenario of the promise:
functions is rejected, the promise should also be rejected with the first rejection reason.Note: The resolved values returned need not include timestamps, and this implementation must not use the JavaScript built-in Promise.all function.
// Example 1
Input: functions = [ () => new Promise(resolve => setTimeout(() => resolve(5), 200)) ]
Output: {"t": 200, "resolved": [5]}
Explanation:
The only function resolves after 200 milliseconds with a value of 5.
// Example 2
Input: functions = [
() => new Promise(resolve => setTimeout(() => resolve(1), 200)),
() => new Promise((resolve, reject) => setTimeout(() => reject("Error"), 100)) ]
Output: {"t": 100, "rejected": "Error"}
Explanation:
Since one of the Promises is rejected, the returned Promise is also rejected with the same error reason at the same time.
// Example 3
Input: functions = [
() => new Promise(resolve => setTimeout(() => resolve(4), 50)),
() => new Promise(resolve => setTimeout(() => resolve(10), 150)),
() => new Promise(resolve => setTimeout(() => resolve(16), 100))
]
Output: {"t": 150, "resolved": [4, 10, 16]}
Explanation: All promises resolve with a value, and after the last promise resolves, the returned promise also resolves.
async function promiseAll(promiseArray) {
const resultArray = []
let resolveCount = 0
const len = promiseArray.length
return new Promise((resolve, reject) => {
promiseArray.forEach((promiseFunc, index) => {
promiseFunc().then(res => {
resultArray[index] = res
resolveCount++
if(resolveCount === len){
resolve(resultArray);
}
}).catch(reject)
})
})
}
const arr = [
() => new Promise(resolve => setTimeout(() => resolve(4), 50)),
() => new Promise(resolve => setTimeout(() => resolve(10), 150)),
() => new Promise(resolve => setTimeout(() => resolve(16), 100))
]
const res = await promiseAll(arr)
console.log('res',res)