One Pager Cheat Sheet
Promise.all()
is used to take an iterable of promises as an input, wait for them to resolve, and return a single Promise that resolves to an array of the results,but will reject with the first rejection message or error
if any of the input promises are rejected.- We can implement an
all
function that takes an array of promises and returns aPromise
that resolves to an array of return values from the input.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
22
Promise.all = (promises) => {
return new Promise((resolve, reject) => {
const results = [];
if (!promises.length) {
resolve(results);
return;
}
let pending = promises.length;
promises.forEach((promise, idx) => {
Promise.resolve(promise).then((value) => {
results[idx] = value;
pending--;
if (pending === 0) {
resolve(results);
}
}, reject);
});
});
};
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
That's all we've got! Let's move on to the next tutorial.
If you had any problems with this tutorial, check out the main forum thread here.