Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
789 views
in Technique[技术] by (71.8m points)

node.js - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
        });
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...