setTimeout,setImmediate,nextTick

nodejs 中实现异步通常有标题中三种方法,但是如果不理解它们在node event loop中的生命周期的具体执行位置,很容易遇到一些莫民奇妙的困惑.

比如:

let bar;

function asyncApi(callback) {
    callback()
}

asyncApi(value => {
  console.log(value + "bar", bar); 
});

bar = 1;

what will happen?
因为其实是同步方法,所以
undefinedbar undefined
言归正传 if ... then ?

const fs = require("fs");
let bar;

function someAsyncApiCall(callback) {
    setImmediate(callback, "immediate");
    setTimeout(()=>{callback('setTimeout')}, 0)
}

someAsyncApiCall(value => {
  console.log(value + " bar", bar); 
});

bar = 1;

what if ?

const fs = require("fs");
let bar;

function someAsyncApiCall(callback) {
    setTimeout(()=>{callback('setTimeout')}, 0)
    setImmediate(callback, "immediate");
}

someAsyncApiCall(value => {
  console.log(value + " bar", bar); 
});

bar = 1;

what if?

const fs = require("fs");
let bar;

function someAsyncApiCall(callback) {
    setTimeout(()=>{callback('setTimeout')}, 0)
    setImmediate(callback, "immediate");
    process.nextTick(callback, "nextTick");
}

someAsyncApiCall(value => {
  console.log(value + " bar", bar); 
});

bar = 1;

what if ?

const fs = require("fs");
let bar;

function someAsyncApiCall(callback) {
    fs.readFile('', ()=>{
        setImmediate(callback, "immediate");
        setTimeout(()=>{callback('setTimeout')}, 0)
        process.nextTick(callback, "nextTick");
    })
}

someAsyncApiCall(value => {
  console.log(value + " bar", bar); 
});

bar = 1;

wait for your explaination
haha

附送一张nodejs event loop 生命周期图:

image.png

then how about?

let a ;
setTimeout(()=>{
    console.info(a)
},0)

setImmediate(()=>{
    a=1
})

And ?

let a ;
setTimeout(()=>{
    console.info(a)
},0)

process.nextTick(()=>{
    a=1
})

你可能感兴趣的:(setTimeout,setImmediate,nextTick)