Promise.all takes a list of promises and gives back one promise. It resolves when every promise in the list is ready, with all their values in an array, in the input order, not the order they finished. If any promise rejects, it rejects at once with that error and doesn't wait for the others.
You would use it to start several slow jobs together and wait for all of them:
const [user, cart] = await Promise.all([getUser(), getCart()]);
Here user is always the value of getUser(), even when getCart() finishes first. Plain values in the list count as ready, and an empty list resolves at once with [].
The check builds lists with wait(ms, value), a promise that is ready with value after ms, and fail(ms, message), one that rejects. It must print, among others:
promiseAll([wait(300, "Mug"), wait(100, "Pen"), wait(200, "Lamp")]) 100 ms: 'Pen' is ready 200 ms: 'Lamp' is ready 300 ms: 'Mug' is ready 300 ms: promiseAll resolves with [ 'Mug', 'Pen', 'Lamp' ] promiseAll([wait(500, "Teapot"), fail(100, "Plant is sold out")]) 100 ms: a promise rejects with Error: Plant is sold out 100 ms: promiseAll rejects with Error: Plant is sold out 500 ms: 'Teapot' is ready promiseAll([]) 0 ms: promiseAll resolves with []
Your task: write promiseAll(list) without using Promise.all. It returns a new promise that resolves with the values in the input order, rejects with the first rejection, and resolves with [] for an empty list.
Assignment
Follow the Coding Tutorial to return a new promise, wait for each item of the list, put each value in its place, count how many are left, and handle the empty list.
Hint
Put each value at results[i], not with push: a later promise may finish first. results.length can't tell you that all are in, so count down a number instead. Promise.resolve(x) turns a plain value into a promise too.
Free plan: 30 tutor messages. PRO is unlimited.
