【问题标题】:not able to push data into combineddata array无法将数据推送到组合数据数组中
【发布时间】:2016-06-12 21:25:09
【问题描述】:

我无法将数据推送到闭包函数内的组合数据数组中。我发现我需要将闭包用于与数据库相关的程序。我是节点 js 和 javascript 的新手。它的异步性质像这样让我陷入很多麻烦。任何人都可以帮助我如何处理这个问题。

combineddata=[];
        if(err){
            res.send(err);
        }else{
            for(i=0;i<data.length;i++){

            (function(){
                x=i;

                teststats.addTestStats.find({Testid:data[x].Testid},function(err,testdata){
                    if(err){
                        res.send(err);
                    }else{
                        //console.log(testdata+"no"+x+"yes"+i);
                        console.log(x,i)
                        stat.push(testdata);
                        combineddata.push("examplepush");
                    }

                });
            })();


            }
        }
res.send(combineddata);

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    我假设“无法推送”是指您推送到 combineddata"examplepush" 未显示在您的 HTTP 响应中。这是因为数据库查询是异步执行的,回调中的推送代码实际上是在您完成 res.send 并从处理程序返回之后运行的。

    你可以做的是重构你的代码,这样你只需要在那里执行一个查询而不是循环中的几个查询,然后你就可以在数据库查询回调中执行 res.send。

    尝试使用类似这样的东西作为构建块而不是 for 循环:

    var testIds = data.map(function (elem) { return elem.Testid });
    teststats.addTestStats.find({Testid: {$in: testIds}}, function (err, testdata) {
      res.send(testdata) // Testdata is now an array matching all Testid's you queried for
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多