Sean H
Sean H

Reputation: 89

Meteor client side asynchronous callback

How to get value return by the asynchronous call back in the client side of meteor before stack continue to execute? something like :

var result=function(str){
      Meteor.call("getSearch",str,function(err,res){
    if (err)
      throw new Error(err.message);
    else 
      return res
      });
    };

    var final=result(text);
    console.log(final);

How can I get the value of final before it print out? Thanks.

Upvotes: 0

Views: 335

Answers (1)

Carson Moore
Carson Moore

Reputation: 1287

With asynchronous functions, the easiest way to do something with the result is going to be do it in the callback function itself. So for instance, in this case, if you want to log the result to the console, you'll have to do this:

var result=function(str){
  Meteor.call("getSearch",str,function(err,res){
    if (err)
      throw new Error(err.message);
    else 
     console.log(res); // rather than returning
  });
};

result(text);

More generally, if you have a complicated function you want to run the return value through, you can call that also:

var my_totally_complicated_fn = function(arg) { 
  ... // do a bunch of stuff
}

var result=function(str){
  Meteor.call("getSearch",str,function(err,res){
    if (err)
      throw new Error(err.message);
    else 
     my_totally_complicated_fn(res); 
  });
};

result(text);

Upvotes: 1

Related Questions