Promise.all find reject index

Findling the index of promise which lead to fail promise.all

by Varun Sukheja

HTML

<script src="https://cdn.jsdelivr.net/gh/eu81273/jsfiddle-console/console.js"></script>

JavaScript

const promise1 = Promise.resolve(3);
const promise2 = Promise.reject(42);
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

/* Promises array */
const promises = [promise1, promise2, promise3];

/* This does the wonder */
const mappedPromises = promises.map((promise, i) =>
  promise.catch((err) => {
    throw {
      err,
      index: i
    };
  })
);

/* Using Promise.all() as usual */
Promise.all(mappedPromises)
  .then(
    (results) => {
      console.log('everything worked fine, I got ', results);
    })
  .catch(
    (error) => {
      console.error(`promise ${error.index + 1} i.e. index=${error.index} failed with msg`, error.err)
    });