Javascript 同步Meteor.methods函数中的MeteorJS异步代码
如何让client method.call等待异步函数完成?当前,它到达函数的末尾并返回未定义的 Client.jsJavascript 同步Meteor.methods函数中的MeteorJS异步代码,javascript,meteor,Javascript,Meteor,如何让client method.call等待异步函数完成?当前,它到达函数的末尾并返回未定义的 Client.js Meteor.call( 'openSession', sid, function( err, res ) { // Return undefined undefined console.log( err, res ); }); Server.js Meteor.methods({ openSession: function( session_id )
Meteor.call( 'openSession', sid, function( err, res ) {
// Return undefined undefined
console.log( err, res );
});
Server.js
Meteor.methods({
openSession: function( session_id ) {
util.post('OpenSession', {session: session_id, reset: false }, function( err, res ){
// return value here with callback?
session_key = res;
});
}
});
我能从中找到答案。为了从method.call中运行异步代码,您可以使用Futures,这会强制函数等待
var fut = new Future();
asyncfunc( data, function( err, res ){
fut.ret( res );
});
return fut.wait();
更新:对不起,我应该更仔细地阅读这个问题。看起来这个问题也被问到并得到了回答
除了期货之外,另一个需要考虑的模式是用异步调用返回的数据更新另一个模型,然后订阅该模型的变化。
从中可以看出,回调函数的结果参数
(err,res)
应该包含openSession函数的输出。但是您没有从openSession函数返回任何值,因此返回值未定义
您可以测试以下内容:
客户:
Meteor.call('foo', function(err, res) {
console.log(res); // undefined
});
Meteor.call('bar', function(err, res) {
console.log(res); // 'bar'
});
服务器:
Meteor.methods({
foo: function() {
var foo = 'foo';
},
bar: function() {
var bar = 'bar';
return bar;
}
});
Meteor的最新版本提供了未记录的
Meteor.\u wrapAsync
函数,该函数将具有标准(err,res)
回调的函数转换为同步函数,这意味着当前光纤将在回调返回之前产生,然后使用Meteor.bindEnvironment确保保留当前Meteor环境变量(例如Meteor.userId())
一个简单的用法如下所示:
asyncFunc = function(arg1, arg2, callback) {
// callback has the form function (err, res) {}
};
Meteor.methods({
"callFunc": function() {
syncFunc = Meteor._wrapAsync(asyncFunc);
res = syncFunc("foo", "bar"); // Errors will be thrown
}
});
您可能还需要使用function#bind
,以确保在包装asyncFunc
之前使用正确的上下文调用它。
有关更多信息,请参阅:我认为不可能从客户端在meteor方法中执行异步任务。在服务器中使用光纤可能是一种选择。我本来打算建议future/promise,但没有意识到它内置在Meteor中。到处都是有用的。你是一个直截了当的G。这是一些即时呼叫级别的代码。期货不再是Meteor core的一部分,所以这不再有效。@iiz肯定是的<代码>var Future=Npm.require('fibers/Future')代码>