Wait for Meteor.call to finish

Hi,

I have the following code:

Meteor.call('httPost',post,function(err, response) {
            Session.set('serverResponse', response)});

console.log(Session.get('serverResponse'));

The problem is on the first run the serverResponse is “undefined” but running Session.get(‘serverResponse’) on the console reveals a result - this make me think that the script continues before the Method is finished.

How can I prevent that?

tnx!

Meteor.call accepts a function argument as its last parameter. This function is called a ‘callback’ and is executed after the data from Meteor.call is returned. That’s why your session is not set if you try to print it in the next line. From the docs:

Optional callback, which is called asynchronously with the error or result after the method is complete.

You can convert your Meteor.call into a synchronous function using Meteor.wrapAsync(). Docs.

Do whatever you gotta do in the callback.

Meteor.call runs asynchronously. That means that it returns immediately. So that means your Session.get could run before your Session.set

Meteor.call('httpPost', function (err, response) {
  if (!err) {
    MyCollection.update(response._id, {
      $set: { status: 'complete' }
    });
  } else {
    alert('Stop right there criminal scum.')
  }
});
1 Like

tnx @corvid - that’s what I did, after I couldn’t get the Meteor.wrapAsync() to work (tnx @timfletcher)…