setImmediate vs. nextTick

后端 未结 7 654
野的像风
野的像风 2020-11-22 12:26

Node.js version 0.10 was released today and introduced setImmediate. The API changes documentation suggests using it when doing recursive nextTick

7条回答
  •  北海茫月
    2020-11-22 13:09

    As an illustration

    import fs from 'fs';
    import http from 'http';
    
    const options = {
      host: 'www.stackoverflow.com',
      port: 80,
      path: '/index.html'
    };
    
    describe('deferredExecution', () => {
      it('deferredExecution', (done) => {
        console.log('Start');
        setTimeout(() => console.log('TO1'), 0);
        setImmediate(() => console.log('IM1'));
        process.nextTick(() => console.log('NT1'));
        setImmediate(() => console.log('IM2'));
        process.nextTick(() => console.log('NT2'));
        http.get(options, () => console.log('IO1'));
        fs.readdir(process.cwd(), () => console.log('IO2'));
        setImmediate(() => console.log('IM3'));
        process.nextTick(() => console.log('NT3'));
        setImmediate(() => console.log('IM4'));
        fs.readdir(process.cwd(), () => console.log('IO3'));
        console.log('Done');
        setTimeout(done, 1500);
      });
    });
    

    will give the following output

    Start
    Done
    NT1
    NT2
    NT3
    TO1
    IO2
    IO3
    IM1
    IM2
    IM3
    IM4
    IO1
    

    I hope this can help to understand the difference.

    Updated:

    Callbacks deferred with process.nextTick() run before any other I/O event is fired, while with setImmediate(), the execution is queued behind any I/O event that is already in the queue.

    Node.js Design Patterns, by Mario Casciaro (probably the best book about node.js/js)

提交回复
热议问题