我有一个方法,我想在执行回调之前做一些请求和计算。我发现很多人建议使用async模块但是在调用回调之前它仍然没有等待回调完成。这是我想要完成的示例代码。
loop.js
var ex_obj = require('./ex_obj');
var array2loop = [
arr1 = new ex_obj(),
arr2 = new ex_obj(),
arr3 = new ex_obj()
];
var loop = function(){
for(var i=0; i < array2loop.length; i++){
array2loop[i].incrementNumber(function log(){
console.log('Should fire last: ' + array2loop[i].number);
});
}
setTimeout(loop, 5000);
};
loop();
ex_obj.js
var async = require('async');
var ex_obj = function(){
var self = this;
self.number = 0;
self.incrementNumber = function(callback){
self.number = ++self.number;
// This setTimeout is a placeholder for a url request
// that I don't know how long will take.
setTimeout(function(){
console.log('Should fire first: '+self.number);
}, 2000);
callback();
};
};
module.exports = ex_obj;
按原样运行时,我会得到以下内容
Should fire last: 1
Should fire last: 1
Should fire last: 1
Should fire first: 1
Should fire first: 1
Should fire first: 1
Should fire last: 2
...etc
如果我进行了以下更改,我会收到“无法读取未定义的属性”编号错误:
ex_obj.js
self.incrementNumber = function(callback){
self.number = ++self.number;
setTimeout(function(){
console.log('Should fire first: '+self.number);
callback();
}, 2000);
};
所以我尝试使用async.series仅在超时运行后调用回调
ex_obj.js
async.series([
function(){
setTimeout(function(){
console.log('Should fire first '+self.number);
}, 2000)}],
callback()
);
这仍然导致上面的输出。我知道这是一个常见问题,但我似乎无法找到解决回调内部回调的解决方案。感谢您提供任何帮助!
答案 0 :(得分:0)
我猜你需要这样的东西:
var ex_obj = function () {
var self = this;
self.number = 0;
self.incrementNumber = function (callback) {
self.number = ++self.number;
setTimeout(callback, 2000);
console.log('Should fire first: ' + self.number);
};
};
var array2loop = [
arr1 = new ex_obj(),
arr2 = new ex_obj(),
arr3 = new ex_obj()
];
var loop = function () {
array2loop.forEach(function (element) {
element.incrementNumber(function () {
console.log('Should fire last: ' + element.number);
});
});
setTimeout(loop, 5000);
};
loop();
输出:
Should fire first: 1
Should fire first: 1
Should fire first: 1
Should fire last: 1
Should fire last: 1
Should fire last: 1
Should fire first: 2
Should fire first: 2
Should fire first: 2
Should fire last: 2
Should fire last: 2
Should fire last: 2
...