用额外的数据扩展承诺
我使用kriskowal/q
promise库来处理http请求,但为了简化,我们假设我有一个dynamic创build的promises
数组,并将其推送到promises
数组:
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.all
保证结果顺序 ,所以你可以使用results
中每个元素的索引来查找id。 在你的例子中:
Q.all(promises).then(function (results) { results.forEach(function(results, i) { var id = ids[i]; }) });