Scriptdrill

Level 5: Async and functions Exercise 75 of 76 Free

Write your own Promise.all

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Write `Promise.all` by hand, without calling it. `values` is an array of Promises and plain values. Return a Promise that resolves with an array of the results in the order of `values` (not in the order they finish), once every one of them has resolved. Plain values count as already resolved. If any Promise rejects, the returned Promise rejects with that error straight away, without waiting for the rest. An empty array resolves with `[]`. Tests run on a fake clock: `setTimeout`, `clearTimeout` and `Date.now` are simulated, so waits are instant and exact.

What this exercise teaches

Writing the result at its own index keeps the order of the input however the Promises finish, and a counter (not the array length) tells when all of them are in. Promise.resolve lets plain values go down the same path. The empty array needs its own line, because no callback ever runs to resolve it.

A hint if you get stuck

Return `new Promise((resolve, reject) => ...)`. Loop with the index, wrap each value in `Promise.resolve`, store its result at `results[i]` and count how many are still pending. Resolve when the count reaches 0, and remember the empty array, where the count starts at 0.

Try it now, free, no account needed

Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.

Open this exercise

More exercises in Async and functions