Pregunta

I would like to maintain an aggregate of intermediate results when executing a series of Q.all tasks.

Concretely the problem is as follows:

var Obj = function(first, second) { 
    return { 
        stuff: first, 
        otherStuff: [1,2],
        nextStuff: function() { return Q.fcall(function() { return second }) }
    }
};                                     

var ab = Q.fcall(function() { return Obj("A", "B"); });
var cd = Q.fcall(function() { return Obj("C", "D"); });

var promises = [ab, cd];

What I would like is a result of [{stuff: obj, nextStuff: "B"}, {stuff: obj, nextStuff: "D"}]

Right now I keep a reference to the previous result and map over them using underscore.js like so

Q.all(promises).then(function(stuffs) { 
    var promiseNextStuff = _.map(stuffs, function(x) { return x.nextStuff(); });
    Q.all(promiseNextStuff).then(function(nextStuffs) { 
        var result = _.map(_.zip(stuffs, nextStuffs), function(obj) { 
            return _.object(["stuff", "nextStuff"], obj); 
        });
        console.log("result", result);
    });
});

... but I'm sure there is a better way in Q

http://jsfiddle.net/joelkuiper/xY8Ew/2/

¿Fue útil?

Solución

I wouldn't wait for all promises (or all nextStuffPromises) before translating the results back to the objects:

Q.all(_.invoke(promises, "then", function(obj) {
// or:_.map(promises, function(p) { return p.then(function(obj) {
    return obj.nextStuff().then(function(nextStuff) {
        return {
            prevStuff: obj,
            nextStuff: nextStuff
        };
    }); // });
})).then(console.log.bind(console, "result:"));

There isn't any way in Q to access previous results other than by nesting then calls.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top