nodejs 按顺序异步调用

	var arr = [],
	slice = arr.slice,
	AsyncCallback = function() {
		this.init.apply(this, arguments);
	};
	AsyncCallback.prototype = {
		constructor : AsyncCallback,
		init : function() {
			this.__list = slice.apply(arguments), this.__index = 0;
		},
		//添加需要执行的函数
		//函数原型
		//function(handler) {
		//	handler(res, err);
		//	//handler必须被调用,才能执行下一个函数
		//	//该handler由AsyncCallback.handler截获
		//}
		attach : function() {
			this.__list = this.__list.concat(slice.apply(arguments));
			return this;
		},
		//回调函数,截获AsyncCallback.attach中handler(res, err)触发的动作
		//并执行下一个函数
		handler : function(handler) {
			var callback = this;
			callback.state = 1,
			callback.__list[callback.__index++](function(res, err) {
				callback.__handler(res, err, handler);
			});
			return callback;
		},
		//私有函数
		__handler : function(res, err, handler) {
			handler(res, err);
			if (0 === callback.state) {
				this.init();
			} if (this.__index < this.__list.length) {
				this.handler(handler);
			} else {
				this.init(),
				this.__release && this.__release();
			}
		},
		//设置函数组运行完毕后执行的操作
		release : function(handler) {
			this.__release = handler;
			return this;
		},
		//终止函数组运行
		abort : function() {
			this.state = 0;
			return this;
		}
	};
	var http_test = function(callback, flag) {
		var http = require("http");
		http.get("http://www.sohu.com", function(res) {
			var chunk = [];
			res.on("data", function(data) {
				chunk.push(data);
			}).on("end", function() {
				var result = {
					flag : flag,
					status : res.statusCode,
					statusText : res.statusMessage
				};
				"function" === (typeof callback) ? callback(result) : (callback.async.abort() && callback.handler(result));
			});
		}).on("error", function(err) {
			callback(null, err);
		});
	};
	var callback = new AsyncCallback();
	callback.attach(function(handler) {
		http_test(handler, 100);
	}).attach(function(handler) {
		http_test({async : callback, handler : handler}, 200);
	}, function(handler) {
		http_test(handler, 300);
	}).release(function() {
		console.log("AsyncCallback released");
	}).handler(function(res, err) {
		if (err) console.log(err);
		console.log(res);
	});

你可能感兴趣的:(nodejs)