FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Promise.all

20mins

Implement a function promiseAll(promises) that mimics the behavior of Promise.all().

The function:

  • Takes an array of values or promises.
  • Returns a single Promise that:
    • Resolves with an array of resolved values (in the same order).
    • Resolves immediately with [] if the input array is empty.
    • Rejects immediately if any promise rejects, with the reason of the first rejection.
    • Rejects if the argument is not an array.

This is commonly used to run multiple asynchronous operations concurrently and wait for all results before proceeding.

Example

// Resolved example const p0 = Promise.resolve(3); const p1 = 42; const p2 = new Promise((resolve) => setTimeout(() => resolve("foo"), 100)); await promiseAll([p0, p1, p2]); // [3, 42, "foo"] // Rejection example const p0 = Promise.resolve(30); const p1 = new Promise((_, reject) => setTimeout(() => reject("An error occurred!"), 100)); try { await promiseAll([p0, p1]); } catch (err) { console.log(err); // "An error occurred!" }

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests