Q Promise Nodejs如何解决循环问题

Naz*_*udi 7 loops node.js promise q

我有用nodejs编写的代码让我使用混淆 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();

});
Run Code Online (Sandbox Code Playgroud)

我想在循环内的第二个函数中的数据可以推入结果

所以我以前的数据是这样的

[
    {
        id: 1,
        item: 1,
        hero: 2
    },
    {
        id: 1,
        item: 1,
        hero: 2
    }
]
Run Code Online (Sandbox Code Playgroud)

所以这样

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

    }
]
Run Code Online (Sandbox Code Playgroud)

我已经尝试了几种方法,首先输入命令deferred.resolve(); 循环中的语句只显示1个数据有什么解决方案吗?

Ben*_*aum 10

而不是deferred.resolve()立即解析的数组,使用Q.all等待一组承诺:

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)
});
Run Code Online (Sandbox Code Playgroud)

甚至更好:

theFunction()
.then(function(data) {
    return Q.all(data.map(function(item)
        return secondFunc(item)
        .then(function(data2) {
            item.more = data2.item;
            return item;
        });
    });
});
Run Code Online (Sandbox Code Playgroud)