gpt4 book ai didi

javascript - 从嵌套在函数中的 Node.js 回调返回对象

转载 作者:行者123 更新时间:2023-12-03 10:44:26 24 4
gpt4 key购买 nike

假设我有以下函数,其中包含同步文件系统调用:

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

最佳答案

处理这个问题的正常方法是将外部函数也变成异步函数。如果您无法控制调用函数的生命周期,但可以控制稍后使用其返回值的位置,则可以使用 Promise 来表示内部异步函数的 future 值,并“解开”该 Promise当需要时。

例如,使用Bluebird promise 库:

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
});

关于javascript - 从嵌套在函数中的 Node.js 回调返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28625192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com