Richard Richard - 1 month ago 19
TypeScript Question

Javascript: Synchronize observable events

I am using Ionic2 with Meteor. I

observe
a
Cursor
, for when it gets added to or updated.

public messages: Mongo.Cursor<Message>;

this.messages.observe({
added: (message) => this.addMessageToLocal(message),
changed: (message) => this.updateMessageToLocal(message)
});


In my case, the
added
event gets triggered before the
changed
event. However, they run asynchronously. I would like the event that is triggered first (
added
) to finish before the next event (
changed
) starts.

Is this possible?

Thank you

UPDATE

I am thinking of maintaining a flag, that says when one job is busy, and the other one must wait until it is finished. Is this advisable?

Answer

In the asynchronous world of javascript you cannot control (much as you would like to) the order of execution.

There are two ways to deal with this

1) Get used to it, and write your code accordingly

2) Do the first thing, and then start the second thing in the callback response for the first thing (although in this case I don't think you can)

Comments