← All tasksJavaScript · Middle

promiseAll: your own Promise.all

Write a function promiseAll(items) that works like Promise.all without using it. It returns a promise with an array of results in the order of items, not in the order they finish.

Items can be promises or plain values. The first error rejects the whole promise immediately. An empty array gives [].

Tests (6)

  1. expect(await promiseAll([Promise.resolve(1), 2, Promise.resolve(3)])).toEqual([1, 2, 3]);
  2. const slow = wait(40).then(() => 'slow');
    const fast = wait(10).then(() => 'fast');
    expect(await promiseAll([slow, fast])).toEqual(['slow', 'fast']);
  3. expect(await promiseAll([])).toEqual([]);
  4. const error = new Error('boom');
    await expect(promiseAll([wait(20), Promise.reject(error)])).rejects.toBe(error);
  5. const started = Date.now();
    await promiseAll([wait(50), wait(50), wait(50)]);
    expect(Date.now() - started < 120).toBe(true);
  6. expect(promiseAll([1])).toBeInstanceOf(Promise);