Nazril Faudi Nazril Faudi - 2 months ago 11
Node.js Question

Q Promise Nodejs how to resolve in loop

i have code written in nodejs make me confusying using

Q Promises


theFunction()
.then(function(data) {
var deferred = Q.defer()
var result = [];
for(i=0; i < data.length; i++) {

secondFunc(data.item)
.then(function(data2) {
data.more = data2.item
});
result.push(data);

}

deferred.resolve(result);
deferred.promise();

});


i want data in second function inside loop can push into result

so my previous data is like this

[
{
id: 1,
item: 1,
hero: 2
},
{
id: 1,
item: 1,
hero: 2
}
]


and so like this

[
{
id: 1,
item: 1,
hero: 2,
more: {
list: 1
}
},
{
id: 1,
item: 1,
hero: 2,
more: {
list: 4
}

}
]


I've tried several ways start by entering the command
deferred.resolve (); statement in the loop and only showing 1 data
have any solution ?

Answer

Instead of a deferred.resolve() on an array which will resolve immediately, use Q.all which waits for an array of promises:

theFunction()
.then(function(data) {
    var result = [];
    for(var i=0; i < data.length; i++) (function(i){
        result.push(secondFunc(data[i].item)
        .then(function(data2) {
            data[i].more = data2.item;
            return data[i];
        }));
    })(i); // avoid the closure loop problem
    return Q.all(result)
});

Or even better:

theFunction()
.then(function(data) {
    return Q.all(data.map(function(item)
        return secondFunc(item)
        .then(function(data2) {
            item.more = data2.item;
            return item;
        });
    });
});