return value from asynchronous function in Nodejs

后端 未结 2 610
礼貌的吻别
礼貌的吻别 2020-12-12 02:11

I am using nodejs to query data from Mongodb throught Mongoose. After get the data, I want do something on that data before responding it to client. But I can not get the re

2条回答
  •  臣服心动
    2020-12-12 03:05

    Keep in mind that by the time the console.log functions are executed, the query has not yet finished, thus will display "undefined". That's the essence of nodeJS's asynchronicity.

    For example,

    Person.find().exec(function (err, docs) {
        for (var i=0;i

    If you want to actually wait until the query is finished so you can use the values, I would recommend moving the app.listen(3000); and console.log('Listening on port 3000'); into the function's final callback.

    I'd also recommend you to check out this node module. It will help you build asynchronous / synchronous functions more easily, and allow you to execute a callback when all the asynchronous functions are finished.

提交回复
热议问题