user925885
user925885

Reputation:

Asynchronicity in Javascript

I have a question about asynchronicity in Javascript. From what I've been able to read up on about is that Javascript only uses one thread but is able to handle events asynchronously.

I have the following code:

game.next();
this.autopilot();

Now, I need the function game.next to finish before the this.autopilot function is called. Does Javascript actually wait until game.next is finished or does it run this.autopilot istantly?

If it does, does a callback solve the problem?

The next function with a callback:

Game.prototype.next = function(callback) {
    // Code

    if(callback !== undefined) {
        callback();
    }
};

The calling function using that callback:

game.next(function() {
    this.autopilot();
}.bind(this));

Upvotes: 3

Views: 948

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234795

In your code, game.next() must return before this.autopilot() is called.

However, it is possible that game.next() starts an asynchronous process (e.g., an Ajax call) and returns before the process completes. If you want to defer execution of this.autopilot() until that process is complete, then you would need some sort of callback mechanism. game.next() would have to pass the callback function on to whatever asynchronous processing was taking place. (Executing the call-back just before returning—as you suggest in your question—would be wrong, as this would also happen before the asynchronous process completed.)

Upvotes: 3

jsalonen
jsalonen

Reputation: 30481

Yes, you can use a callback to make sure game.next() finishes before this.autopilot(). But there is a trick: you just cannot paste some callback after whatever code. Whether or not you need to implement a callback depends on whether game.next() function is asynchronous.

Example of a synchronous function that doesn't need a callback:

function next() {
   Game.x += 1;
}

Example of an asynchronous function that needs a callback to preserve the execution order:

function next(callback) {
   window.setTimeout(function() {
       if(callback !== undefined) { /* etc. */ }
   }, 0);
}

Upvotes: 1

Related Questions