← 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 [].
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
Tests (6)
expect(await promiseAll([Promise.resolve(1), 2, Promise.resolve(3)])).toEqual([1, 2, 3]);
const slow = wait(40).then(() => 'slow'); const fast = wait(10).then(() => 'fast'); expect(await promiseAll([slow, fast])).toEqual(['slow', 'fast']);
expect(await promiseAll([])).toEqual([]);
const error = new Error('boom'); await expect(promiseAll([wait(20), Promise.reject(error)])).rejects.toBe(error);
const started = Date.now(); await promiseAll([wait(50), wait(50), wait(50)]); expect(Date.now() - started < 120).toBe(true);
expect(promiseAll([1])).toBeInstanceOf(Promise);