node.js - NodeJS - using Q to do async operations on an array of objects, with a twist -


i'm new q , promises, , have been struggling issue days. i'm trying iterate through variable-length array of records, using id each record in async call retrieve object (in case redis).

the twist need combine data record data retrieved object, creating new array these combined objects returned.

my failing code looks this:

arrayofthingrecords = [... array of small objects, each '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)     }); //     }; // stuff arrayofthingobjects... 

i know using foreach wrong, because executes before promises return. i've been trying work q.all() , q.settled(), , building array of promises, etc, i'm confused , suspect/hope may making harder needs be.

don't use global arrayofcombinedobjects = [] manually fill. resolve promises result values of respective operation. example,

q.ninvoke(redisclient, "hgetall", thingrecord.thingid) .then(function(thingobject) {     return { //  ^^^^^^         thingstufffromrecord: thingrecord.thingstufffromrecord,         thingstufffromobject: thingobject.thingstufffromobject     }; }); 

becomes promise for object.

now, using q.all correct approach. takes array of promises, , combines them promise array of results. need build array of promises - array of promises these objects above. can use foreach iteration , push put array together, using map easier. becomes

var arrayofthingrecords = [... array of small objects, each 'thingid'...]; var arrayofpromises = arrayofthingrecords.map(function(thingrecord) {     return q.ninvoke(redisclient, "hgetall", thingrecord.thingid) //  ^^^^^^ let promise part of new array     .then(function(thingobject) {         return {             thingstufffromrecord: thingrecord.thingstufffromrecord,             thingstufffromobject: thingobject.thingstufffromobject         };     }); }); q.all(arrayofpromises).then(function(arrayofcombinedobjects) {     // stuff arrayofthingobjects... }); 

Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -