Javascript Asynchrony

I have a question about asynchrony in Javascript. From what I was able to read, is that Javascript uses only one thread, but is capable of handling events asynchronously.

I have the following code:

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

Now I need to execute the game.next function before the this.autopilot function is this.autopilot . Is Javascript really waiting for game.next complete or is this.autopilot istantly executing it?

If so, is the callback performing the problem?

The following callback function:

 Game.prototype.next = function(callback) { // Code if(callback !== undefined) { callback(); } }; 

The calling function using this callback:

 game.next(function() { this.autopilot(); }.bind(this)); 
+4
source share
2 answers

Yes, you can use the callback to ensure that game.next() ends before this.autopilot() . But there is a trick: you simply cannot insert a callback after any code. Whether you need to make a callback depends on whether the function game.next() asynchronous.

An example of a synchronous function that does not need a callback:

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

An example of an asynchronous function that requires a callback to preserve execution order:

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

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

However, it is possible that game.next() starts an asynchronous process (for example, an Ajax call) and returns before the process ends. If you want to delay the execution of this.autopilot() until this process is complete, you will need some kind of callback mechanism. game.next() would have to pass a callback function to any asynchronous processing. (Making a callback before returning & mdash, as you suggest in your question, would be wrong, as it would also happen before the asynchronous process completes.)

+4
source

Source: https://habr.com/ru/post/1492161/


All Articles