var fs = require('fs'); fs.readFile(__dirname,() =>{ setTimeout(() =>{ console.log('setTimeout') }) setImmediate(() =>{ console.log('setImmediate') process.nextTick(() =>{ console.log('nextTick3') }) }) process.nextTick(() =>{ console.log('nextTick1') }) process.nextTick(() =>{ console.log('nextTick2') }) }) // nextTick1 nextTick2 setImmediate nextTick3 setTimeout
var http = require('http'); function compute(){ process.nextTick(compute) } http.createServer(function(req,res){ // 服务请求的时候,还能抽空进行一些计算任务; res.writeHead(200, {'Content-type': 'text/plain'}) res.end('hello world'); }) compute()
function asyncFake(data,callback){ // 同步执行 if(data === 'foo') callback(true) else callback(false) } asyncFake('bar',function(result){ // this callback is actually called synchronously! })
为何这样很差呢?看下面nodejs文档里的一段代码node
var client = net.connect(8124, function(){ console.log('client connect'); client.write('world'); // 会报错 })
在上面的代码里,若是由于某种缘由,net.connect()变成同步执行的了,回调函数就会马上被执行,所以回调函数写到客户端的变量就用于不会被初始化了; 这种状况下咱们就能够用process.nextTick()把上面的asyncFake改为异步执行的;app
function asyncReal(data, callback){ process.nextTick(function(){ callback(data === 'foo') }) }
EventEmitter 有两个比较核心的方法,on和Emit。node自带的发布/订阅模式;异步
var EventEmitter = require('events').EventEmmiter; function StreamLibrary(resourceName){ this.emit('start') } StreamLibrary.prototype.__proto__ = EventEmitter.prototype; // inherit from EventEmitter
var stream = new StreamLibrary('fooResouce'); stream.on('start', function(){ console.log('Reading has started') })
以上代码在new StreamLibrary的时候,已经触发了emit,此时 尚未订阅,console.log不会执行 解决方案以下:用异步方法包装async
function StreamLibrary(resource){ var self = this; // 保证订阅在发布以前 process.nextTick(function(){ self.emit('start'); }) // read from the file,and for every chunck read.do; this.emit('data', chunkRead) }
发布订阅模式函数
const EventEmitter = require('events').EventEmitter; class App extends EventEmmiter{ } let app = new App(); app.on('start',() =>{ // 订阅 console.log('start'); }) app.emit('start') // emit 触发,emit是个同步的方法 console.log(111); // 若是须要emit是异步的,能够经过三种异步方法去包装 // start 111