简体   繁体   English

NodeJS Express异步问题

[英]NodeJS Express Async issue

I have this function which gets some data from my database but i'm having a trouble calling the function and getting the proper response 我有这个功能,可以从数据库中获取一些数据,但是我在调​​用该功能并获得正确的响应时遇到了麻烦

  function getEvents()
  {
    var x = [];
    var l = dbCollection['e'].find({}).forEach(function(y) {
    x.push(y);
  });

 return x;
});

and another function which calls this function but it always returns undefined. 另一个函数调用此函数,但始终返回未定义。 How can i make the function wait till mongoose has finished filling up the array? 我怎样才能让函数等到猫鼬填满数组?

Thanks for the help! 谢谢您的帮助! My life 我的生活

dbCollection['e'].find is called non-blocking way so you are returning x before filling. dbCollection['e'].find被称为非阻塞方式,因此您在填充之前将返回x You need to use callbacks or some mongoose promises. 您需要使用回调或一些猫鼬的诺言。 You can get all returning values from database like following snippet 您可以从数据库获取所有返回值,例如以下代码段

function getEvents(callback) {
    dbCollection['e'].find({}, function(error, results) {
        // results is array.
        // if you need to filter results you can do it here
        return callback(error, results); 
    })
}

Whenever you need to call getEvents function you need to pass a callback to it. 每当需要调用getEvents函数时,都需要向其传递回调。

getEvents(function(error, results) {
    console.log(results); // you have results here
})

You should read mongoose docs for how queries work. 您应该阅读猫鼬文档 ,了解查询的工作方式。

There is also support for promises in mongoose. 猫鼬也支持诺言。 You can check this url for more information about promises. 您可以检查此网址以获取有关诺言的更多信息。

The solution proposed by @orhankutlu should work fine. @orhankutlu提出的解决方案应该可以正常工作。

I will give another solution using promise. 我将使用promise给出另一个解决方案。 You can choose one between these two solutions depending on your style of programming. 您可以根据编程风格在这两种解决方案中选择一种。

Solution using promise: 使用promise的解决方案:

function getEvents() {
    return new Promise(function(resolve, reject){
        dbCollection['e'].find({}, function(error, results) {
           if (error) return reject(error);

           var x = [];
           results.forEach(function(y){
              x.push(y);
           });
           // forEach() is a blocking call, 
           // so the promise will be resolved only 
           // after the forEach completes
           return resolve(x); 
        });
    });
};

Calling getEvents(): 调用getEvents():

getEvents().then(function(result){
    console.log(result);   //should print 'x'
}).catch(function(err){
    // Handle error here in case the promise is rejected
});

I will encourage you to try both the approaches, ie, using callbacks and using promises. 我鼓励您尝试两种方法,即使用回调和使用Promise。 Hope you find it useful! 希望你觉得它有用!

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

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