ilrein
ilrein

Reputation: 3923

Promises in MeteorJS

I'm making an Async call on the server side, through Meteor.methods.

I would like my client to await for the async response before attempting to run any further logic.

I need help understanding how to leverage Async/Promises with remote HTTP requests.

Currently, I have a very simple event setup:

  'click #getOrders': function() {
    Meteor.call('getOrders', function(err, data) {
      if (!err) {
        console.log(data);
      }
    })
  }

Which then calls:

var shopifyAPI = Meteor.npmRequire('shopify-node-api');
var Shopify = new shopifyAPI({
  shop: 'xxxxx.myshopify.com', 
  shopify_api_key: 'xxxxxx', 
  access_token: 'xxxxx' 
});

Meteor.methods({
  'getOrders': function() {

    var promise = new Promise(function(resolve, reject) {
      Shopify.get('/admin/orders/count.json', function(err, res) {
        if (err) reject(err);
        else resolve(res);
      });
    });

    promise.then(function(data) {
      return data;
    })

  }
})

When I click my event handler, I can see my server logs are correctly receiving data. Adding a console.log under promise.then confirms that the promise code is working.

However, my client side console.log is always undefined, due to it returning a result before my async response has come back. How can I handle this properly?

Upvotes: 1

Views: 375

Answers (1)

ryan0319
ryan0319

Reputation: 412

You should return the promise.

return promise;

After returning, on the client side call:

data.then(function(data) {
  console.log(data);
});

Upvotes: 1

Related Questions