使用额外数据扩展承诺

Extend promise with extra data

我正在使用 kriskowal/q promise 库来处理 http 请求,但为了简化案例,我们假设我有一个动态创建并推送到 promises 数组的 promise 数组:

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' ]

问题是 - 是否有可能以某种方式将 id 分配给承诺,以便稍后在 all 执行时获得它?

假设我们不能修改返回值(它来自 API,我不能用额外的数据扩展它)。

Q.allguarantees result order,所以可以通过results中各个元素的index来查找id。在你的例子中:

Q.all(promises).then(function (results) {
  results.forEach(function(results, i) {
    var id = ids[i];
  })
});