user2693017
user2693017

Reputation: 1860

Meteor async function in meteor-method with database update

for the last few hours, I have been trying to get an async method to play nice with meteor methods and its database.

While using wrapAsync works great for simple method calls, I struggling with getting it to work in this case.

Any help would be much appreciated.

https://docs.meteor.com/api/core.html#Meteor-wrapAsync

The async method in question:

chargebee.subscription.list({
  limit : 5, 
  "plan_id[is]" : "basic", 
  "status[is]" : "active",
  "sort_by[asc]" : "created_at"
}).request(function(error,result){
  if(error){
    //handle error
    console.log(error);
  }else{
    for(var i = 0; i < result.list.length;i++){
      var entry=result.list[i]
      console.log(entry);
      var subscription = entry.subscription;
      var customer = entry.customer;
      var card = entry.card;
    }
  }
});

What I tried and didn't work:

    try {
        var result = Meteor.wrapAsync(chargebee.subscription.list, chargebee.subscription)({
            limit: 5,
            "customer_id[is]": Meteor.userId(),
            "status[is]": "active",
            "sort_by[asc]": "created_at"
        }).request();

        if (result.list[0]) {
            const subscription = result.list[0].subscription;
            console.log("quantity", subscription.plan_quantity);

            Subs.update(
                {
                    owner_id: this.userId
                }, {
                    $set: {
                        quantity: subscription.plan_quantity
                    }
                }
            );
        }
    } catch(error) {
        console.log(error);
    }

Upvotes: 0

Views: 117

Answers (1)

Styx
Styx

Reputation: 10076

You should wrap in Meteor.wrapAsync the async method itself. In your code you're wrapping the chargebee.subscription.list only, and it isn't async (based on your example).

You should wrap .request() method instead (not its call):

// Call to `subscription.list()` extracted
// for better understanding
try {
  var list = chargebee.subscription.list({
    limit: 5,
    "customer_id[is]": Meteor.userId(),
    "status[is]": "active",
    "sort_by[asc]": "created_at"
  });
  var result = Meteor.wrapAsync(list.request)();
  // process result
} catch(error) {
  // process error
}

Upvotes: 1

Related Questions