简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM