简体   繁体   中英

Understanding Javascript asynchronous blocks and callbacks

doA( function1(){
    doC();

    doD( function2(){
        doF();
    } )

    doE();
} );

doB();

Assuming doA() and doD() to be asynchronous calls we have the sequence: A->BC->D->E->F

  1. call A, returns and sends function1 to Queue,
  2. call B,
  3. Nothing more to execute -> Executes what's in the Queue -> call C,
  4. call D, returns and sends function2 to Queue,
  5. call E,
  6. 6-Nothing more to execute -> call F.

Is there something actually correct about my reasoning? Am I completely wrong?

This question came from reading " You don't know Javascript " by Kyle Simpson.

Seems like the book has done a good job, you've understood the basics well :-)

Some minor points may render your reasoning more precise:

  1. " Assuming doA() and doD() to be asynchronous calls " - let's say that doA and doB are ("asynchronous") functions that asynchronously call the callback functions passed to them as an argument. And we might further limit them to call the respective callback exactly once (to avoid confusion).

  2. " sends function1 to Queue " - it might not do so immediately. That's the whole point of background processing, the callback is only queued when the respective task (started by doA() or doD() ) has finished. A simple example would be a timeout. If there are multiple asynchronous callbacks awaited, they might be called in arbitrary order, depending on how long their tasks did take.
    Similarly, when there is nothing more to execute, it might need to wait for something to appear in the queue, and idle as long as there is nothing.

  3. " what's in the Queue -> call C " - in fact, function1 is in the queue, which then calls doC() and the others. You shouldn't skip this step :-) Same for calling doF() .

You are almost there.

It is really hard to understand how the behavior will actually turn out. It can vary on how long and intensive each function call is in comparison to others running asynchronously.

Another part that you are missing is that "function1" will not inherently call on return of function "doA". For "function1" to even run, it is require for "doA" at sometime during its run to issues a callback(). Otherwise, "doA" will simply return and none of the nested functions you have written will be called.

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