说我有以下函数,其中包含一个同步文件系统调用:
var foo = function(){
var numbytes = fs.readSync(...);
return numbytes;
}
那里没有问题。
但是如果我使用带有回调的异步函数,那么:
var baz = function(){
var numbytes = fs.read(...,function(){
// return numbytes; (wrong)
});
//return numbytes; (wrong)
};
如何从baz函数中正确返回与numbytes绑定的值?
在Meteor Node.js框架中,这可能是这个问题的一个答案:
Meteor.wrapAsync(func, [context]) Anywhere
Wrap a function that takes a callback function as its final parameter. On the server, the wrapped function can be used either synchronously (without passing a callback) or asynchronously (when a callback is passed). On the client, a callback is always required; errors will be logged if there is no callback. If a callback is provided, the environment captured when the original function was called will be restored in the callback.
Arguments
func Function
A function that takes a callback as its final parameter
context Object
Optional this object against which the original function will be invoked
答案 0 :(得分:1)
处理此问题的常用方法是将外部函数也转换为异步函数。如果您无法控制调用函数的生命周期,但可以控制以后使用其返回值的位置,则可以使用promise来表示内部异步函数的未来值,并且&#34 ;解开"在需要时承诺。
例如,使用Bluebird promises库:
var fs = require("fs");
var Promise = require("bluebird");
var baz = function(){
var promise = new Promise(function(resolve, reject){
fs.readFile("file.json", function(err, val) {
if (err) {
reject(err);
}
else {
resolve(val);
}
});
});
return promise;
});
var bazPromise = baz();
bazPromise.then(function(value){
// deal with value
}, function(error){
// deal with error
});