Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor: Calling an asynchronous function inside a Meteor.method and returning the result

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   } }); 
like image 592
Joseph Tura Avatar asked Sep 24 '12 17:09

Joseph Tura


1 Answers

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.

like image 84
Joscha Avatar answered Sep 19 '22 07:09

Joscha