Q Promise Nodejs 如何在循环中解析 [英] Q Promise Nodejs how to resolve in loop

查看:24
本文介绍了Q Promise Nodejs 如何在循环中解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 nodejs 编写的代码让我使用 Q Promises

感到困惑

theFunction().then(函数(数据){var deferred = Q.defer()var 结果 = [];for(i=0; i < data.length; i++) {secondFunc(data.item).then(功能(数据2){data.more = data2.item});结果.推(数据);}deferred.resolve(result);deferred.promise();});

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

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

<预><代码>[{编号:1,项目:1,英雄:2},{编号:1,项目:1,英雄:2}]

像这样

<预><代码>[{编号:1,项目:1,英雄:2,更多的: {清单:1}},{编号:1,项目:1,英雄:2,更多的: {名单:4}}]

我尝试了几种方法,从输入命令开始deferred.resolve();循环中的语句,仅显示 1 个数据有什么解决办法吗?

解决方案

代替 deferred.resolve() 在将立即解析的数组上,使用 Q.all> 等待一系列承诺:

theFunction().then(函数(数据){var 结果 = [];for(var i=0; i < data.length; i++) (function(i){result.push(secondFunc(data[i].item).then(功能(数据2){数据[i].more = data2.item;返回数据[i];}));})(一世);//避免闭环问题返回 Q.all(结果)});

甚至更好:

theFunction().then(函数(数据){返回 Q.all(data.map(function(item)返回 secondFunc(item).then(功能(数据2){item.more = data2.item;归还物品;});});});

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 ?

解决方案

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

这篇关于Q Promise Nodejs 如何在循环中解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆