简体   繁体   English

如何在节点js中执行forloop

[英]How to perform forloop in node js

Acoording to the data available ui should get 2 reults but getting only one since i put res.send in the looop so it is getting ended ,can anyone help me out please....... 根据可用的数据,ui应该得到2个结果,但是由于我将res.send发送到了循环中,所以它只能得到一个结果,所以它结束了,任何人都可以帮帮我........

exports.getrequestsdetails = function(req, res) {
    var params = req.params;
    console.log(params)
    var record = db.collection('requests');
    var item = {
        "sent_id": params.id,
        "status": 1
    }
    record.find(item).toArray((err, result) => {
        if (err) {
            return
        }
        if (result) {
            for (var i in result) {
                var id = result[i].recieved_id;
                var profile = db.collection('profile');
                profile.find({
                    '_id': new ObjectId(id)
                }).toArray((err, resp) => {
                    if (err) {
                        return
                    }
                    if (resp) {
                        console.log(resp);
                    } else {}
                });
            }
            res.send(resp);
        } //end of if loop
        else {
            response = {
                status: 'fail',
                data: []
            };
        }

    });

}

You can send only one response back to a request. 您只能将一个回复发送回请求。

Define a variable outside the for loop, append records to it and then send it after the for loop has ended. 在for循环外定义一个变量,将记录追加到该变量,然后在for循环结束后将其发送。

exports.getrequestsdetails = function(req, res) {
var params = req.params;
console.log(params)
var record = db.collection('requests');
var item = {
    "sent_id": params.id,
    "status": 1
}

var resList = [];

record.find(item).toArray((err, result) => {
        if (err) {
            return
        }
        if (result) {
            for (var i in result) {
                var id = result[i].recieved_id;
                var profile = db.collection('profile');
                profile.find({
                    '_id': new ObjectId(id)
                }).toArray((err, resp) => {
                        if (err) {
                            return
                        }
                        if (resp) {
                           console.log(resp);
                           resList[i] = resp;
                        }
                        else{
                      }
                });
            }
        }//end of if loop
        else {
             resList = {
                status: 'fail',
                data: []
              };
         }
        res.send(resList);
       });

You can push all the resp in list array and send after completing loop . 您可以push所有resp push送到list数组中,并在完成loop后发送。

Like this: 像这样:

    exports.getrequestsdetails = function(req, res) {
    var params = req.params;
    console.log(params);

    var record = db.collection('requests');
    var item = {
        "sent_id": params.id,
        "status": 1
    };

    record.find(item).toArray((err, result) => {
        if (err) {
            return err;
        }
        if (result) {
            var list = [];
            for (var i in result) {
                var id = result[i].recieved_id;
                var profile = db.collection('profile');
                profile.find({
                    '_id': new ObjectId(id)
                }).toArray((err, resp) => {
                    if (err) {
                        return err;
                    }
                    else{
                        list.push(resp);
                        console.log(resp);
                        if(i===result[result.length-1]){
                             res.send(list);
                        }
                    }
                });
            }

        } //end of if loop
        else {
            response = {
                status: 'fail',
                data: []
            };
        }

    });
};

Hope this work for you 希望这项工作对您有帮助

Don't use for loop in asynchronous mode. 不要在异步模式下使用for循环。 Use async module instead like below. 改用异步模块,如下所示。

var async = require('async');
exports.getrequestsdetails = function (req, res) {
    var params = req.params;
    console.log(params)
    var record = db.collection('requests');
    var item = {
        "sent_id": params.id,
        "status": 1
    }
    record.find(item).toArray(function (err, result) {
        if (err) {
            return
        }
        if (result) {
            var list = [];
            async.each(result, function (item, cb) {
                var id = item.recieved_id;
                var profile = db.collection('profile');
                profile.findOne({
                    '_id': new ObjectId(id)
                }, function (err, resp) {
                    if (err) {
                        return cb();
                    }
                    if (resp) {
                        list.push(resp);
                        console.log(resp);
                        return  cb();
                    }
                    return cb();
                });
            }, function (err) {
                res.send(list);
            });
        }//end of if loop
        else {
            response = {
                status: 'fail',
                data: []
            };
        }

    });

}

The problem is in getting the profiles. 问题在于获取配置文件。 You are using mongodb's find which is asynchronous . 您正在使用mongodb的find,它是异步的 Therefore in your for cycle you start fetching the profiles, but then you send out the res.send well before the fetching of the profiles is finished. 因此,在您的for周期中,您开始获取配置文件,但是在配置文件获取完成之前,请先发送res.send

The call back from profile.find(... will be executed after the res.send . Apart from this, the resp variable is inside the find callback and you are trying to res.send it outside. 呼叫从后profile.find(...将在执行res.send 。除此之外,该resp变量是查找回调里面,你试图res.send外面。

To deal with this, either you use async or promises . 为了解决这个问题,您可以使用asyncpromises See the below code that uses promises. 请参阅以下使用Promise的代码。

var Promise = require('bluebird')

exports.getrequestsdetails = function(req, res) {
    var params = req.params;
    console.log(params)
    var record = db.collection('requests');
    var item = {
        "sent_id": params.id,
        "status": 1
    }

    record.find(item).toArray((err, result) => {
        if (err) {
            return
        }
        if (result) {

            var profiles_to_get = []
            var profiles = []

            for (var i in result) {
                var id = result[i].recieved_id;
                profiles_to_get.push(get_profile(id, profiles))
            }

            Promise.all(profiles_to_get)
                .then(() => {
                    res.send(profiles);
                })
        } //end of if loop
        else {
            response = {
                status: 'fail',
                data: []
            };
        }

    });

    function get_profile (id, profiles) {
        return new Promise(function (resolve, reject) {
            var profile = db.collection('profile');
                profile.find({
                    '_id': new ObjectId(id)
                }).toArray((err, resp) => {
                    if (err) {
                        reject(err)
                        return
                    }
                    if (resp) {
                        profiles.push(resp)
                        resolve()
                    } else {
                        reject()
                    }
                });
        })
    }

}

How this works is that it creates a list of profiles to find and stores it in the var profiles_to_get = [] . 这是如何工作的,它创建了一个概要文件列表来查找并将其存储在var profiles_to_get = [] The you use Promise.All(profiles_to_get) which will let you do stuff after all the profiles have been fetched. 您可以使用Promise.All(profiles_to_get)来获取所有配置文件后进行处理。

您可以将所有列表添加到数组中,最后在循环后发送数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM