Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MeteorJS async code inside synchronous Meteor.methods function

How to get the client method.call to wait for an asynchronous function to finish? Currently it reaches the end of the function and returns undefined.

Client.js

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;
        });
     }
});
like image 367
Pastor Bones Avatar asked Nov 02 '12 06:11

Pastor Bones


2 Answers

Recent versions of Meteor have provided the undocumented Meteor._wrapAsync function which turns a function with a standard (err, res) callback into a synchronous function, meaning that the current Fiber yields until the callback returns, and then uses Meteor.bindEnvironment to ensure that you retain the current Meteor environment variables (such as Meteor.userId()).

A simple use would be as the following:

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

You may also need to use function#bind to make sure that asyncFunc is called with the right context before wrapping it. For more information see: https://www.eventedmind.com/tracks/feed-archive/meteor-meteor-wrapasync

like image 109
Andrew Mao Avatar answered Oct 08 '22 10:10

Andrew Mao


I was able to find the answer in this gist. In order to run asynchronous code from within a method.call you use Futures which forces your function to wait.

    var fut = new Future();
    asyncfunc( data, function( err, res ){
        fut.ret( res );
    });
    return fut.wait();
like image 25
Pastor Bones Avatar answered Oct 08 '22 09:10

Pastor Bones