I want to call an asynchronous function inside a Meteor method and then return the result from that function to Meteor.call.
(How) is that possible?
Meteor.methods({ my_function: function(arg1, arg2) { //Call other asynchronous function and return result or throw error } });
Use a Future to do so. Like this:
Meteor.methods({ my_function: function(arg1, arg2) { // Set up a future var fut = new Future(); // This should work for any async method setTimeout(function() { // Return the results fut.ret(message + " (delayed for 3 seconds)"); }, 3 * 1000); // Wait for async to finish before returning // the result return fut.wait(); } });
Update:
To use Future starting from Meteor 0.5.1, you have to run the following code in your Meteor.startup method:
Meteor.startup(function () { var require = __meteor_bootstrap__.require Future = require('fibers/future'); // use Future here });
Update 2:
To use Future starting from Meteor 0.6, you have to run the following code in your Meteor.startup method:
Meteor.startup(function () { Future = Npm.require('fibers/future'); // use Future here });
and then use the return
method instead of the ret
method:
Meteor.methods({ my_function: function(arg1, arg2) { // Set up a future var fut = new Future(); // This should work for any async method setTimeout(function() { // Return the results fut['return'](message + " (delayed for 3 seconds)"); }, 3 * 1000); // Wait for async to finish before returning // the result return fut.wait(); } });
See this gist.
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