2014-02-06 145 views
0

所以基本上我正在做一个数据库查询,以获得具有特定ID的所有帖子,然后将它们添加到列表,所以我可以返回。但是,在回调完成之前,列表会返回。NodeJS异步回调。如何从异步回调中返回列表?

如何在回调完成之前阻止它被返回?

exports.getBlogEntries = function(opid) { 
    var list12 =[]; 


    Entry.find({'opid' : opid}, function(err, entries) { 

      if(!err) { 
      console.log("adding"); 

      entries.forEach(function(currentEntry){ 


       list12.push(currentEntry); 



      }); 

      } 

      else { 
       console.log("EEEERROOR"); 
      } 

      //else {console.log("err");} 


      }); 
    console.log(list12); 
    return list12; 
    }; 

回答

0

ALL回调是异步的,所以我们没有任何保证,如果他们将在我们离开他们的顺序正好运行。

要解决它,使这一进程“同步”,并保证订单executation你有两种解决方案

  • 首先:使嵌套列表中的所有过程:

代替这个:

MyModel1.find({}, function(err, docsModel1) { 
    callback(err, docsModel1); 
}); 

MyModel2.find({}, function(err, docsModel2) { 
    callback(err, docsModel2); 
}); 

使用这个:

MyModel1.find({}, function(err, docsModel1) { 
    MyModel2.find({}, function(err, docsModel2) { 
     callback(err, docsModel1, docsModel2); 
    }); 
}); 

最后一个片段上方保证我们MyModel2MyModel1执行后执行

  • :使用一些框架Async。这个框架非常棒,并且有几个帮助函数可以以任何方式执行系列代码,并行,无论我们想要什么。

实施例:

async.series(
    { 
     function1 : function(callback) { 
      //your first code here 
      //... 
      callback(null, 'some result here'); 
     }, 
     function2 : function(callback) { 
      //your second code here (called only after the first one) 
      callback(null, 'another result here'); 
     } 
    }, 
    function(err, results) { 
     //capture the results from function1 and function2 
     //if function1 raise some error, function2 will not be called. 

     results.function1; // 'some result here' 
     results.function2; // 'another result here' 

     //do something else... 
    } 
); 
0

您可以使用同步数据库调用,但这会绕过node.js的概念。

正确的方法是将回调传递给查询数据库的函数,然后调用数据库查询回调中提供的回调函数。

0

如何在回调完成之前阻止它被返回?

回调是异步的,你不能避免这种情况。因此,你一定不要return一个清单。

取而代之的是,当它被填充时,提供一个回调。或者为列表返回一个Promise。例如:

exports.getBlogEntries = function(opid, callback) { 
    Entry.find({'opid': opid}, callback); // yes, that's it. 
              // Everything else was boilerplate code 
}; 
+0

我不确定,你是什么意思。谢谢您的帮助! – blehadfas1

+0

你不了解什么? – Bergi

0

有处理这种情况的另一种方法。您可以使用异步模块,并在forEach完成后再进行回拨。请在下面找到相同的代码片段:

var async = requires('async'); 
exports.getBlogEntries = function(opid) { 
var list12 =[]; 
Entry.find({'opid' : opid}, function(err, entries) { 
    if(!err) { 
     console.log("adding"); 
     async.forEachSeries(entries,function(entry,returnFunction){ 
      list12.push(entry); 
     },function(){ 
      console.log(list12); 
      return list12; 
     }); 
    } 
    else{ 
      console.log("EEEERROOR"); 
    } 
    }); 
};