javascript express js通过asynchronous调用

我是新来的js。 我使用快递节点js和mongoose作为mongo orm。

function direct_tags_search_in_db(tags){ var final_results = []; for (var i=0; i<tags.length; ++i) { var tag = tags[i]; Question.find({tags: tag}).exec(function(err, questions) { final_results.push(questions); if (i == tags.length -1 ){ return final_results; } }); } }; 

我得到空的结果,因为发现的asynchronous。 但我不知道这是最好的办法。

Appriciate一点帮助,谢谢。

您经常会发现接受函数作为参数的方法(如Question.find().exec是asynchronous的。 执行networking请求或文件系统操作的方法尤其常见。 这些通常被称为callback。 既然如此,如果在完成asynchronous任务时想要发生某些事情,则还需要实现callback。

另外,您对tag的引用有可能以不希望的方式进行更改。 有一些解决scheme,这里是一个简单的。

 function direct_tags_search_in_db(tags, callback){ var final_results = []; // Array.forEach is able to retain the appropriate `tag` reference tags.forEach(function(tag){ Question.find({tags: tag}).exec(function(err, questions) { // We should be making sure to handle errors if (err) { // Return errors to the requester callback(err); } else { final_results.push(questions); if (i == tags.length -1 ){ // All done, return the results callback(null, final_results); } } }); }); }; 

你会注意到当我们实现自己的callback时,我们遵循与Question.find().exec(function(err, result){});callback相同的通用模式Question.find().exec(function(err, result){}); – 第一个参数是潜在的错误,第二个参数是结果。 这就是为什么当我们返回结果时,我们提供null作为第一个参数callback(null, final_results);

调用此函数的快速示例:

 direct_tags_search_in_db([1, 2, 3], function(err, results){ if (err) { console.error('Error!'); console.error(err); } else { console.log('Final results'); console.log(results); } }); 

解决各种asynchronous目标的另一个select是asynchronous模块,承诺或其他。