Link Promise.all() to array of IDs


I am new to Promises, and would like to know if there’s a way to link the result of Promises.all() to an ID for each promise when it resolves.

I am sending requests to a remote server and fetching some data per request, the problem is that the remote server don’t return the ID, so I have to take care of this myself.

Here’s what I have so far:

const promises = [];
const layers = req.body.layers;
const raw = "some data";
layers.forEach(layer => {
    const requestOptions = {
        method: 'POST',
        body: raw,
        headers: { 'Content-Type': 'application/json' }
    promises.push(fetch(layer.url, requestOptions));
    .then(response => {
        let items = [];
        response.forEach(item => items.push(item.json()));
        return Promise.all(items)
    .then(arr => {
        return res.send({ error: false, success: true, response: arr })
    .catch(err => {
        return res.send({ error: err.message, success: false })

Each layer has a unique ID that should be linked to its corresponding promise. How can I achieve this?

I really appreciate your help, thanks!


Promise.all([p1, p2, p3]) resolves independently but gives us data in the same order of the promise array.

In this example if one promise failed then all the promises will get rejected. The basic concept behind Promise.all() is either all or not at all.

Promise.all([p1, p2, p3]).then(results => {
  let p1Data = results[0];
  let p2Data = results[1];
  let p3Data = results[2];

Handle individual rejection in Promise.all()

//handle individual promise

Promise.all([p1.catch(err => return err), p2.catch(err => return err), p3.catch(err => return err)]).then(results => {
  let p1Data = results[0];
  //if for some reason p2 get rejected then it will hold the error message.
  let p2Data = results[1];
  console.log(p2Data) // will show error data
  let p3Data = results[2];

Answered By – Kapil Sharma

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published