Topic Description

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:

The rejection scenario of the promise:

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.

Answer

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)