process.nextTick

回调函数同步执行

function asyncFake(data, callback) {
    if(data === 'foo') {
        callback(true);
    }else{
        callback(false);
    }

}

asyncFake('bar', function(result) {
    // this callback is actually called synchronously!
    console.log(result);
})
console.log("#############");


/*
运行结果:
false
#############*/

回调函数异步执行

process.nextTick()可以确保asyncReal的回调总是在其他同步代码(console.log("#############"))运行完成后,event loop开始前调用的

function asyncReal(data, callback) {
    process.nextTick(function() {
         callback(data === 'foo');
    });
}

asyncReal('bar', function(result) {
    console.log(result);
})

console.log("#############");

/*
运行结果:
#############
false*/
const EventEmitter = require('events');
const util = require('util');

function MyEmitter() {
    EventEmitter.call(this);

    // 使用nextTick,可以等待下面的同步代码,myEmitter.on('event',。。),执行完后,再触发event事件
    //如果不使用nextTick,直接触发event事件,myEmitter.on('event',。。)可能都没有执行,就不会对event事件处理
    process.nextTick(function() {
        this.emit('event');
    }.bind(this));
}
util.inherits(MyEmitter, EventEmitter);

const myEmitter = new MyEmitter();
//对event事件的处理方法
myEmitter.on('event', function() {
    console.log('an event occurred!');
});

猜你喜欢

转载自www.cnblogs.com/moris5013/p/10774937.html
今日推荐