Synchronous call to the API


#1

I have a registered helper that makes call to the server method. The server method calls API and returns the api-response to the helper.

UI.registerHelper('userList', function () {
     //Call to the server method
     Meteor.call('userAccountsApi', cid, extUserId, loginType, function (error, result) {
         if (error) {
             console.log("error occured on receiving data on server. ", error);
             return null;
         }
         return result;
});

This is the server side method:

userApi: function (params) {
     var url = "URL created using the parameters";
     var result,listOfAccounts;
     try {
         //API call
         result = HTTP.get(url);
     } catch (error) {
    	// We got an error
     }
     if (result.statusCode == 200) {
          var respJson = JSON.parse(result.content);
    	  return respJson;
    }
    //logic to return the error message
    return error;
}

I want registered helper to call the server method synchronously and complete execution only when it gets the data from the server method.


#2

From docos

asyncCallback Function
Optional callback, which is called asynchronously with the error or result after the method is complete. If not provided, the method runs synchronously if possible (see below).

So you are actually specifying it should be async by providing your callback.


#3

Perhaps you’re looking for this?


#4

I tried using the methods from this package but they do not seem to work synchronously.


#5

Meteor methods always run asynchronously on the client.

[From the docs][1]:

On the client, if you do not pass a callback and you are not inside a stub, call will return undefined, and you will have no way to get the return value of the method. That is because the client doesn’t have fibers, so there is not actually any way it can block on the remote execution of a method.

The way around this that I have found is to store the result in a ReactiveVar and return the reactive var in a helper.
[1]: http://docs.meteor.com/#/full/meteor_call