简体   繁体   中英

Javascript asynchronous callbacks

I have studied and studied, but I don't understand asynchronous situations in javascript. Consider the following blocking behavior:

var data = getData();
alert(data);

function getData(){

    //takes a while to do stuff
    return stuff;
}

Instead it should be:

getData(function(data){
    alert(data);
});

function getData(callback){

    callback();

}

How does this avoid blocking? I just don't seem to grasp how this is any different than just calling one function from within another function. Aren't I just passing a function definition as the callback to getData() for it to use later? It seems like I would still be waiting on the callback function. I can't seem to understand how this allows the functions to run in parallel. Maybe someone could outline the execution step by step for me or something.

Even thought Javascript is typically seen as a NOT multi-threaded programming language, which is correct since it doesn't have concurrency features like eg threads in Java but deep down our Javascript engines like V8... It actually is multi-threaded. Hah.

So what really happens when you invoke an asynchronous method like below?

$.get( "www.helloWorld.com/test.html", function( data ) {
  alert( "Load was performed." );
});
alert("Hey there!");

For what $.get() is, refer to https://api.jquery.com/jquery.get/

When your code gets to the async $.get() method, a thread is actually spawned from the Javascript engine to go away and do stuff seperately from your main thread.

In this case a HTTP GET request is made against the www,helloWorld.com endpoint to fetch data for the test.html page.

While this is all happening, separately from your main thread, your main thread does not wait for its return, instead a callback function is passed to the $.get() API to instruct it to 'call me back'/run the logics within it when it has finished its job. In this example we do a simple alert("Load was performed") , while in real world scenario you typically want to read the response data and popular a variable or paste the text onto a textbox.

Hence, instead of waiting for $.get() to finish, the code actually moves on to the next line to do more stuff. For this instance, alert("Hey there"); .

If you think about this scenario again, the async function $.get() is actually not blocking the main thread from processing other lines of code, while $.get() is running behind the scene. Therefore the async programming model is considered to be non-blocking.

The non-blocking concept is also similar to NodeJs's event driven architecture which might be worth a read.

https://nodesource.com/blog/understanding-the-nodejs-event-loop/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM