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