Last active
June 13, 2023 18:48
-
-
Save eoikonomou/ad47de6eea86f4d4b7729acc5c745130 to your computer and use it in GitHub Desktop.
Promise all function replacement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function promiseAll(promises, results = []) { | |
return new Promise((resolve, reject) => { | |
const results = []; | |
if (!promises.length) { | |
return resolve(results); | |
} | |
let pendingPromises = promises.length; | |
promises.forEach((promise, index) => { | |
promise | |
.then(result => { | |
results[index] = result; | |
pendingPromises -= 1; | |
if (pendingPromises === 0) { | |
return resolve(results); | |
} | |
}) | |
.catch(err => reject(err)); | |
}); | |
}); | |
} | |
function promise(fail = false) { | |
return new Promise((resolve, reject) => { | |
if (fail) { | |
return reject('error!'); | |
} | |
return resolve('ok'); | |
}); | |
} | |
promiseAll([promise(), promise(true)]) | |
.then(result => console.log(result)) | |
.catch(err => console.log(err)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment