我在打印这两个语句时遇到问题,我有两个函数
var mongoose = require( 'mongoose' );
var_show_test = mongoose.model( 'test' );
exports.showTest = function(req,res) {
var jsonString = [];
var_show_test.find(function (err, testa) {
console.log("In find");
});
console.log("In function");
}
但它正在按顺序打印语句
In function
In find
我想要的是按顺序打印语句,例如
In find
In function
我知道这是由于异步调用而发生的,我对回调函数有点困惑。如何处理这个问题以便按顺序打印语句。
最佳答案
对于初学者,如果您只想登录控制台,那么您可以将第二个 console.log
放入回调中 -
exports.showTest = function(req,res) {
var jsonString = [];
var_show_test.find(function (err, testa) {
console.log("In find");
console.log("In function");
});
}
但是,如果您想在 find 回调执行后执行函数/方法,那么您需要在此处使用闭包 -
exports.showTest = (function (callback) {
return function(req,res) {
var jsonString = [];
var_show_test.find(function (err, testa) {
console.log("In find");
callback();
});
}
})(callbackFunc);
function callbackFunc() {
console.log('In my callback!');
}
关于javascript - Node js 中的异步函数处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20113220/