Chris Wheadon
Chris Wheadon

Reputation: 840

How do you ensure an update has finished in meteor before running a find?

I have a fairly typical need, to ensure an insert / update has finished before I run a find. The code goes something like this:

//Update my collections
Messages.insert({author:_id,text:text});
Authors.update({_id:_id},{$inc:{messages:1}});

//Wait until the update / insert has finished

//Perform some actions on the collections just updated
var author = Authors.findOne({task:taskId},{sort:{'messages':1}});
//Do some more complex stuff...

While in most cases this would be fine as asynchronous calls, with the dom updating as and when things complete, in my case it is essential that the insert and update have completed before I run the function call.

Do I need to perform the insert and update as a server side call with a callback function, or is there some way I could do this on the client side?

At the moment I have something like:

Meteor.call("recordMessage", _id, text, 
    function(err, out){postMessage(_id)}
);

which works - but I'd like to know if I could do this on the client side.

Upvotes: 0

Views: 335

Answers (1)

Christian Fritz
Christian Fritz

Reputation: 21374

Isn't that what the optional callback arguments are for?

var author;
Messages.insert({author:_id, text:text},
                function(err, result) {
                    Authors.update({_id: result},
                                   {$inc: {messages:1}},
                                   function(err, result) {
                                       author = Authors.findOne({task:taskId}, 
                                                                {sort:{'messages':1}});
                                   }
                                  );
                });

Upvotes: 1

Related Questions