Quantcast
Channel: CNode:Node.js专业中文社区
Viewing all articles
Browse latest Browse all 14821

12行代码让回调变成顺序执行

$
0
0

function Next(){ this.funcs = []; } Next.prototype.next = function(callback){ this.funcs.push(callback); return this; } Next.prototype.start = function(){ var func = this.funcs.shift(); func && func.apply(this,arguments); } exports = module.exports = Next; 下面是测试代码 var Next = require(’./next.js’); var next = new Next(); var fs = require(‘fs’);

next.next(function(a){ fs.stat(__filename, function (e,stat) { if(e) throw e; console.log(a); next.start(stat); }) }).next(function(stat){ fs.access(__filename, function (e) { console.log(‘this file size=’ + stat.size); next.start( e ? false : true); }) }).next(function(exists){ console.log('exists = '+exists); }).start(‘start’);

console.log(‘helloworld’+ next);


Viewing all articles
Browse latest Browse all 14821

Trending Articles