1

I'm using kriskowal/q promise library to handle http requests, but to simplify the case, let's assume I have an array of promises created dynamically and pushed to the promises array:

var promises = [],
    ids = ['foo', 'bar', 'buz'];

ids.forEach(function(id){
  var promise = Q.fcall(function () {
    return 'greetings with ' + id;
  });

  promises.push(promise);
});

// and handle all of them together:
Q.all(promises).then(function (results) {
  console.log(results);
});

// gives:
[ 'greetings with foo',
  'greetings with bar',
  'greetings with buz' ]

The question is - is it possible to assign somehow an id to the promise to obtain it later in all execution ?

Let's assume that we cannot modify the returned value (it comes from the API and I cannot extend it with extra data).

hsz
  • 148,279
  • 62
  • 259
  • 315
  • `Promise.all` [guarantees the order of results](http://stackoverflow.com/a/28066851/2806996), so can you use the index of each element in `results` to look up the id (trivially in your example)? – joews Oct 30 '15 at 11:39
  • @joews ...aaand the problem is gone. Thanks. – hsz Oct 30 '15 at 11:41
  • Now with correct link - my comment referred to ES6 `Promise.all`, but `Q.all` makes the same guarantee. – joews Oct 30 '15 at 11:46

1 Answers1

1

Q.all guarantees result order, so you can use the index of each element in results to look up the id. In your example:

Q.all(promises).then(function (results) {
  results.forEach(function(results, i) {
    var id = ids[i];
  })
});
hsz
  • 148,279
  • 62
  • 259
  • 315
joews
  • 29,767
  • 10
  • 79
  • 91