nextTick vs setImmediate, visual explanation

后端 未结 5 1703
一整个雨季
一整个雨季 2020-12-04 05:02

I\'m very confused about the differences between nextTick and setImmediate. I\'ve read all the documentation about them on the internet but I still don\'t understand how the

5条回答
  •  温柔的废话
    2020-12-04 05:34

    I think all the answers above are obsolete, because I got different answers constantly with the current version of nodejs and it is easy to reason about

    var log=console.log
    log(process.version)
    
    var makeAsyncCall
    if(false)
        makeAsyncCall=setImmediate
    else
        makeAsyncCall=process.nextTick;
    
    makeAsyncCall(function A () {
        makeAsyncCall(function B() {
            log(1);
            makeAsyncCall(function C() { log(2); });
            makeAsyncCall(function D() { log(3); });
        });
        makeAsyncCall(function E() {
            log(4);
            makeAsyncCall(function F() { log(5); });
            makeAsyncCall(function G() { log(6); });
        });
    });
    //1
    //4
    //2
    //3
    //5
    //6
    //in both case
    

    After reading https://github.com/nodejs/node/blob/master/doc/topics/the-event-loop-timers-and-nexttick.md#processnexttick-vs-setimmediate let use start from setImmediate we should keep track of the check queue because it is where the setImmediate callback reside.

    First iteration

    A is push to check queue

    check queue :[A]

    Second iteration

    A is pull out from queue to execute

    During its execution ,it put B and E to queueand then, A complete and start next iteration

    check queue :[B,E]

    Third iteration

    pull out B and push C D

    check queue :[E,C,D]

    Forth iteration

    pull out E and push F G

    check queue : [C,D,F,G]

    Finally

    execute the callbacks in the queue sequentially

    For nextTick case, the queue works exactly the same way,that is why it produce same result

    The different is that :

    the nextTickQueue will be processed after the current operation completes, regardless of the current phase of the event loop

    To be clear,the event loop maintain multiple queues and check queue is just one of them,the node will decide which queue to use based on some rules

    with process.nextTick however,it is sort of bypassing all the rule and execute the callback in nextTick immediately

提交回复
热议问题