在node js中的foreach之后如何发送respose?

时间:2018-08-08 10:21:12

标签: javascript arrays node.js

在我的foreach中,我想将数据推送到一个数组中并将响应发送到客户端。

我正在使用以下内容:

try {
    var allData = [];
    var venuesData = req.db.collection('venues').find({ "restaurantcompetitors": {$exists: true, $ne: null } }, {restaurantcompetitors:1});

    venuesData.forEach(function(data) {
        Array.prototype.push.apply(allData, data);

        res.status(200).send({data: allData, code: 0});
    });

}
catch (error) {
    console.log('Error found in catch: ',error);
}

但是我收到一个错误“标头已发送”,因为我在循环内发送。但是,如果我尝试在循环后推送数据,它将无法推送...

5 个答案:

答案 0 :(得分:3)

您实际上需要使用promise或使用async / await

在此处详细了解异步代码和承诺-https://medium.com/dev-bits/writing-neat-asynchronous-node-js-code-with-promises-32ed3a4fd098

更多有关异步/等待的信息-https://blog.risingstack.com/mastering-async-await-in-nodejs/

try {
    var allData = [];
    var venuesData = await req.db.collection('venues').find({
        "restaurantcompetitors": {
            $exists: true,
            $ne: null
        }
    }, {
        restaurantcompetitors: 1
    });

    // This code won't run until the venuesData has resolved
    venuesData.forEach(function (data) {
        Array.prototype.push.apply(allData, data);


    });
    //Need to send after you have done the loop
    res.status(200).send({
        data: allData,
        code: 0
    });

} catch (error) {
    console.log('Error found in catch: ', error);
}

答案 1 :(得分:1)

try {
      let i = 0 ;
      var allData = [];
      var venuesData = req.db.collection('venues').find({ "restaurantcompetitors": 
            {$exists: true, $ne: null } }, {restaurantcompetitors:1});

      venuesData.forEach(function(data) {
            Array.prototype.push.apply(allData, data);
            i++
      });
      if(i == venuesData.length){   
            res.status(200).send({data: allData, code: 0});
      }
   }catch (error) {
      console.log('Error found in catch: ',error);
}

答案 2 :(得分:0)

try {
var allData = [];
var venues = req.db.collection('venues') // Get model object
venues.find({"restaurantcompetitors": {$exists: true, $ne: null } }, {restaurantcompetitors:1},function(err,venuesData){
    venuesData.forEach(function(data) {
       allData.push(data);  
    });
    res.status(200).send({data: allData, code: 0});
});
}
catch (error) {
console.log('Error found in catch: ',error);
}

答案 3 :(得分:0)

您好,您可以为此使用async模块。

如果尚未安装异步,请通过npm install async --save

安装

首先,我将为您提供静态数据的示例演示,然后是如何在代码中实现

第一:

    var listNumbers = [1,2,3,4,5,6,7,8,9]
    async.each(listNumbers, function(eachNumber, callback) {
        console.log("eachNumber:",eachNumber)
        callback();
    }, function(err) {

        if( err ) {
          console.log('something wrong');
        } else {
          console.log('everything works');
          res.json(listNumbers);
        }
   });

请参阅首先eachNumber将打印9次,然后一切正常。您可以在代码中执行如下操作

第二个:

    var allData = [];
    var venuesData = req.db.collection('venues').find({ "restaurantcompetitors": {$exists: true, $ne: null } }, {restaurantcompetitors:1});
    async.each(venuesData, function(data, callback) {
        Array.prototype.push.apply(allData, data);
        callback();
    }, function(err) {
        if( err ) {
          console.log('something wrong');
          res.status(200).send({message:"something went wrong."});
        } else {
          console.log('everything works');
          res.status(200).send({data: allData, code: 0});
        }
    });

答案 4 :(得分:0)

高级提示:将您的 foreach代码封装在Promise中,并将其他所有承诺放入数组

然后做出回应

var promises = [];

// TODO: Create promise and push it in array i.e. promises.push()
// TODO: Any additional promise: promises.push(newpromise)

// TODO: Then call your code after all has completed
Promise.all(promises).then(() =>
   // put your response here 
   res.status(200).send({data: allData, code: 0});
);

如何创建承诺:https://javascript.info/promise-basics