DEV Community


Discussion on: Today's JavaScript React Dev interview Question

kepta profile image
Kushan Joshi • Edited

The Promise.all question kept me up at night, here is my attempt:

async function promiseAll(promises) {
  return new Promise((resolve, reject) => {
    const result = []; // create an array
    const resolver = (p) => (val) => {
      result[promises.indexOf(p)] = val; // fill it directly, I know this is suboptimal as it creates an array with holes
      // Object.keys helps with finding actual length (without holes) of the array
      if (Object.keys(result).length === promises.length) {
        resolve(Array.from(result)); // Array.from converts the sub-optimal array with holes to a regular array
    promises.forEach((p) => p.then(resolver(p), reject)); // reject early to match Promise.all's early rejection behaviour

The most important thing here is:

  • to early reject, just like Promise.all
  • Keep the order of array
oathkeeper profile image
Divyesh Parmar Author

Wow this is complicated, I need to focus :D