setImmediate vs. nextTick

后端 未结 7 735
野的像风
野的像风 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:01

    Some great answers here detailing how they both work.

    Just adding one that answers the specific question asked:

    When should I use nextTick and when should I use setImmediate?


    Always use setImmediate.


    The Node.js Event Loop, Timers, and process.nextTick() doc includes the following:

    We recommend developers use setImmediate() in all cases because it's easier to reason about (and it leads to code that's compatible with a wider variety of environments, like browser JS.)


    Earlier in the doc it warns that process.nextTick can lead to...

    some bad situations because it allows you to "starve" your I/O by making recursive process.nextTick() calls, which prevents the event loop from reaching the poll phase.

    As it turns out, process.nextTick can even starve Promises:

    Promise.resolve().then(() => { console.log('this happens LAST'); });
    
    process.nextTick(() => {
      console.log('all of these...');
      process.nextTick(() => {
        console.log('...happen before...');
        process.nextTick(() => {
          console.log('...the Promise ever...');
          process.nextTick(() => {
            console.log('...has a chance to resolve');
          })
        })
      })
    })
    

    On the other hand, setImmediate is "easier to reason about" and avoids these types of issues:

    Promise.resolve().then(() => { console.log('this happens FIRST'); });
    
    setImmediate(() => {
      console.log('this happens LAST');
    })
    

    So unless there is a specific need for the unique behavior of process.nextTick, the recommended approach is to "use setImmediate() in all cases".

提交回复
热议问题