salezica
salezica

Reputation: 76909

Meteor: async update subscription

I have a subscription that, after calling ready(), performs a number of updates pulling data from other collections:

Meteor.publish('foo', function() {
  this.ready()

  // Several times:
  var extraData = OtherCollection.findOne(...)
  this.changed(..., extraData)
})

How can I run these updates asynchronously? Each update accesses the database, does some computation, and calls changed on the subscription.

I also need to run code after all updates have finished (resynchronize).

Upvotes: 8

Views: 458

Answers (1)

Kyll
Kyll

Reputation: 7139

Simply save the publish handler and use it later!

var publishHandler;

Meteor.publish('foo', function() {
  publishHandler = this;

  //Do stuff...
});

//Later, retrieve it and do stuff with it
doSomeAsync(Meteor.bindEnvironment(function callback(datum) {
  publishHandler.changed(/* ... */, datum);
}));

//Alternatively with Meteor.setTimeout:
Meteor.setTimeout(function callback() {
  publishHandler.changed(/* ... */, 'someData');
},
10000);

Since it's just in the end a JS object you can also save it in an array or do whatever suits you.
Asynchronously.
Heroically.

Upvotes: 5

Related Questions