我是js新手。 我使用express作为node 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;
}
});
}
};
由于查找是异步的,我得到空结果。但我不知道最好的方法是什么。
希望得到一点帮助,谢谢。
最佳答案
您经常会发现诸如 Question.find().exec
之类接受函数作为参数的方法是异步的。对于执行网络请求或文件系统操作的方法尤其常见。这些通常称为回调。既然如此,如果您希望异步任务完成时发生某些事情,您还需要实现回调。
此外,您对 tag
的引用可能会以不受欢迎的方式发生更改。解决方案有很多种,这里是一个简单的。
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);
}
}
});
});
};
您会注意到,当我们实现自己的回调时,我们遵循与 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);
}
});
解决各种异步目标的另一个选项是 async模块、 promise 或其他。
关于javascript express js 传递异步结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22054025/