循环后如何发送头 [英] How to send headers after loop

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

问题描述

我想找到一个用户,该用户的模型包含一系列城市(例如:[马德里,伦敦,莫斯科,布宜诺斯艾利斯等])

I want to do find an user, whose model contains an array of cities (for example:[Madrid, London, Moscow, Buenos Aires, etc])

这是模型:

var UserSchema = Schema({
    name: String,
    surname: String,
    userName: String,
    email: String,
    password: String,
    rol: String,
    suscriptionDate: Date,
    cities:[String],
    citiesPopulate:[]
});

找到用户后,我想遍历此数组以将每个城市用作参数,以查找我在模型City上拥有的信息,只是将坐标添加到user.citiesPopulate

Once I've found the user, I want to iterate through this array to use each city as the parameter in order to find the info that I have on the model City just to add coords to user.citiesPopulate

function findUsersCities(req,res){
    let id=req.body._id;

    User.findById(id,function(err,userFound){
        if(err){
            console.log(err)
        }else{

            for(let i=0;i<userFound.cities.length;i++){

                City.findOne({'city':userFound.cities[i]},function(err,citiesFound){
                    if(err){
                        console.log(err)
                    }else{
                        userFound.citiesPopulate.push(citiesFound.coords);
                        console.log(userFound)
                    }
                })
            } 

        }
    })
}

而且,一旦将每个城市的所有信息都添加到userFound.citiesPopulate(现在只是带有一对坐标的数组),我想使用 res.status(200).send({userFound })在邮递员控制台上查看结果,如下所示(三个城市和三对坐标):

And, once all the info of every single city has been added to userFound.citiesPopulate (by now just arrays with a pair of coordinates), I want to use res.status(200).send({userFound}) to see the result on my postman console, something like this(three cities and three pairs of coordinates):

{ cities: [ 'Bilbao', 'Madrid', 'Barcelona' ],
  citiesPopulate: [ [ -3.68, 40.4 ], [ -2.97, 43.25 ], [ 2.18, 41.38 ] ],
  _id: 5c82c2e5cfa8d543d0133dd6,
  name: 'pruebas35',
  surname: 'pruebas35',
  userName: 'pruebas35',
  email: 'pruebas35@prueba.es',
  password: '$2a$10$eSue5gw7r4dFPtwD8qzJhODcvvNFaRkeQYRAOPO9MCBsy3Djhkffq',
  rol: 'user',
  suscriptionDate: 2019-03-08T19:30:45.075Z,
  __v: 0 }

但是,如果我在循环中键入 res.status ,则会将其发送出去,而我将无法获取全部信息.

But if I type the res.status into the loop, it is sent and I can´t get the whole information.

我想知道一个解决方案.

I'd like to know a solution for this, please.

推荐答案

正如卡洛斯(Carlos)所指出的那样,由于数据库请求的异步特性,这将无法正常工作.我这样做的方法是使用async/await使代码同步,如下所示:

As pointed out by Carlos, this won't work because of the asynchronous nature of database requests. The way I would do it is to use async/await to make the code synchronous, like this:

function findUsersCities(req,res){
    let id=req.body._id;

    User.findById(id,async function(err,userFound){
        if(err){
            console.log(err)
        }else{
            try {

                for(let i=0;i<userFound.cities.length;i++){

                    let cityFound = await City.findOne({'city':userFound.cities[i]});

                    userFound.citiesPopulate.push(cityFound.coords);
                }

                //complete userFound
                console.log(userFound);

            } catch (e) {
                console.log(e);
            }

        }
    })
}

请注意在User.findById的回调函数中使用关键字async.如果await功能位于带有async关键字标记的函数中,则只能使用该功能.

Notice the use of the keyword async in the callback function from User.findById. You can only use the await feature if it is inside a function marked with the async keyword.

此外,当您未为任何Mongoose查询函数指定回调函数时,它会返回Promise,并且只能在promises上使用await关键字.

Also, when you doesn't specify a callback function to any Mongoose query funcion, it returns a Promise, and you can only use the await keyword on promises.

如果promise解析,代码将继续运行,并且解析的值将位于变量cityFound中,否则(如果promise拒绝),它将抛出执行,因此代码将陷入困境语句,并且拒绝的值将在变量e中.

If the promise resolves, the code will continue to run, and the resolved value will be in the variable cityFound, otherwise (if the promise rejects), it will throw an execption, so the code will fall into the catch statement, and the rejected value will be in variable e.

这篇关于循环后如何发送头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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