同步Meteor.methods函数内的MeteorJS异步代码

Pas*_*nes 8 javascript meteor

如何让客户端method.call等待异步函数完成?目前它到达函数的末尾并返回undefined.

Client.js

Meteor.call( 'openSession', sid, function( err, res ) {
    // Return undefined undefined
    console.log( err, res ); 
});
Run Code Online (Sandbox Code Playgroud)

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;
        });
     }
});
Run Code Online (Sandbox Code Playgroud)

Pas*_*nes 6

我能够在这个要点中找到答案.为了在method.call中运行异步代码,您可以使用Futures强制您的函数等待.

    var fut = new Future();
    asyncfunc( data, function( err, res ){
        fut.ret( res );
    });
    return fut.wait();
Run Code Online (Sandbox Code Playgroud)


And*_*Mao 6

最新版本的Meteor提供了未记录的Meteor._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     
  }
});
Run Code Online (Sandbox Code Playgroud)

您可能还需要使用function#bind以确保asyncFunc在包装之前使用正确的上下文调用它.有关详细信息,请参阅:https://www.eventedmind.com/tracks/feed-archive/meteor-meteor-wrapasync