导出无法工作,因为它在函数外部,而声明在内部.但是如果你把导出放在里面,当你使用你的模块时,你不能确定导出是被定义的.
使用ansync系统的最佳方法是使用回调.您需要导出一个回调分配方法来获取回调,并在异步执行时调用它.
例子:
var foo, callback;
async.function(function(response) {
foo = "foobar";
if( typeof callback == 'function' ){
callback(foo);
}
});
module.exports = function(cb){
if(typeof foo != 'undefined'){
cb(foo); // If foo is already define, I don't wait.
} else {
callback = cb;
}
}
Here 100 is just a placeholder to symbolise an async call.
大体上
var fooMod = require('./foo.js');
fooMod(function(foo){
//Here code using foo;
});
Multiple callback way
如果需要多次调用模块,则需要管理回调数组:
var foo, callbackList = [];
async.function(function(response) {
foo = "foobar";
// You can use all other form of array walk.
for(var i = 0; i < callbackList.length; i++){
callbackList[i](foo)
}
});
module.exports = function(cb){
if(typeof foo != 'undefined'){
cb(foo); // If foo is already define, I don't wait.
} else {
callback.push(cb);
}
}
Here 100 is just a placeholder to symbolise an async call.
大体上
var fooMod = require('./foo.js');
fooMod(function(foo){
//Here code using foo;
});
Promise way
你也可以用promise 来解决这个问题.此方法通过Promise的设计支持多个调用:
var foo, callback;
module.exports = new Promise(function(resolve, reject){
async.function(function(response) {
foo = "foobar"
resolve(foo);
});
});
Here 100 is just a placeholder to symbolise an async call.
大体上
var fooMod = require('./foo.js').then(function(foo){
//Here code using foo;
});
见Promise documentation