PsydeStep PsydeStep - 2 months ago 6
Node.js Question

Meteor method call - wait for method to complete

I am really struggling with Meteor callbacks. I have a client side call to a server side method, but when the callback comes back from the server, I get an undefined result. As far as I can tell, this is because the server is not finished doing the POST but is already sending the callback. I am new to Meteor and this seems really difficult. What I have so far:

Client:

Meteor.call("createCustomer", city, fname, lname, email, function(error, result) {
if (error) {
console.log("error: " + error);
} else {
console.log("result: " + result)
}
});


Server:

Meteor.methods({
'createCustomer': function(city, fname, lname, email) {
HTTP.call("POST", url+'/customer?api_key='+process.env.API_TOKEN ,{
data: {
city: city,
first_name: fnam,
last_name: lname,
email: email
}
}, function (error, result) {
if (error) {
return 'error';
} else {
return'success';
}
});
}
});


I might be doing something really stupid, or it might be more complex than I had anticipated, but any help would go a long way!

Answer

This is what Meteor.wrapAsync is for. It creates a synchronous version of an asynchronous function. Try this:

'createCustomer': function(city, fname, lname, email) {
  var call = Meteor.wrapAsync(HTTP.call, HTTP);
  return call("POST", url+'/customer?api_key='+process.env.API_TOKEN ,{
    data: {
      city: city,
      first_name: fname,
      last_name: lname,
      email: email
    }
  });
}