Created
January 24, 2023 06:52
-
-
Save p0rsche/cfd4b6fcb77f804bbf8ab29a4d1fb6ed to your computer and use it in GitHub Desktop.
Promise.all realizations without Promise.all
This file contains 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
// Simple Promise.all realization | |
function promiseAll(promises) { | |
try { | |
let len = promises.length; | |
let count = len; | |
const results = new Array(len).fill(null); | |
return new Promise((resolve, reject) => { | |
promises.forEach((p, idx) => { | |
p.then((res) => { | |
results[idx] = res; | |
count -= 1; | |
if (count === 0) resolve(results); | |
}).catch((e) => reject(e)); | |
}); | |
}); | |
} catch (e) { | |
return new Error("Error: ", e); | |
} | |
} | |
const p1 = Promise.resolve(1); | |
const p2 = Promise.resolve(2); | |
const p3 = Promise.resolve(3); | |
const perror = Promise.reject('error') | |
promiseAll([p1, p2, p3]).then((res) => console.log(res)).catch(e => console.log(e));; // [1,2,3] | |
promiseAll([p1, p2, perror]).then((res) => console.log(res)).catch(e => console.log(e)); // error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment