【发布时间】:2014-10-11 22:22:57
【问题描述】:
我也是 Q 和 promises 的新手,并且已经为这个问题苦苦挣扎了好几天。我正在尝试遍历一个可变长度的 RECORDS 数组,使用异步调用中每条记录的 ID 来检索 OBJECT(在 redis 的情况下)。
问题是我需要将 RECORD 中的一些数据与检索到的 OBJECT 中的一些数据结合起来,从这些结合的对象中创建一个新数组,然后将其返回。
我的失败代码如下所示:
arrayOfThingRecords = [... an array of small objects, each with a 'thingid'...];
arrayOfCombinedObjects = [];
arrayOfThingRecords.forEach(function(thingRecord) {
Q.ninvoke(redisClient, "HGETALL", thingRecord.thingid)
.then((function (thingObject) {
combinedThingObject = {
thingStuffFromRecord: thingRecord.thingStuffFromRecord,
thingStuffFromObject: thingObject.thingStuffFromObject
};
}).done(function () {
arrayOfCombinedObjects.push(combinedThingObject)
}); //
}; // Then do stuff with arrayOfThingObjects...
我知道使用forEach 是错误的,因为它在承诺返回之前执行。我一直在尝试与Q.all() 和Q.settled() 合作,并建立一系列承诺等,但我完全感到困惑并怀疑/希望我可能会让这变得比需要的更难。
【问题讨论】:
标签: arrays node.js asynchronous promise q