nodejsは順番に非同期で呼び出します.
2257 ワード
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);
});