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;
});
}
});
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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With