MyAsync
by yasumodev
JavaScript
//------------------------------------------------
// MyAsyncモジュール
//------------------------------------------------
var MyAsync = (function() {
var self = {};
// 順次実行
self.run = function()
{
var run_funcs = arguments;
var run_index = -1;
var end_func = null;
var baton = {
index : -1,
result : "",
next : function(result, wait) {
if(result === undefined) result = "";
if(wait === undefined) wait = 0;
run_index++;
baton.index = run_index;
baton.result = result;
setTimeout(function(){
if(run_index < run_funcs.length) {
run_funcs[run_index](baton);
} else if(end_func) {
end_func(baton);
}
}, wait);
},
stop : function(result) {
if(end_func) {
baton.index = run_funcs.length;
baton.result = result;
baton.stopped = true;
baton.stop_index = run_index;
end_func(baton);
}
},
stopped : false,
stop_index : -1,
};
baton.next();
return {
end : function(callback){
end_func = callback;
}
};
};
// 一斉実行
self.all = function()
{
var all_funcs = arguments;
var all_results = [];
var cnt_done = 0;
var cnt_loop = 0;
var end_func = null;
(function loop(){
if(cnt_loop >= all_funcs.length)
return;
var baton = {
index : cnt_loop,
next : function(result) {
if(result === undefined) result = "";
all_results[this.index] = result;
cnt_done++;
// 全処理が終了
if(cnt_done == all_funcs.length){
if(end_func) {
baton.index = all_funcs.length;
baton.results = all_results;
end_func(baton);
}
}
},
stop : function(result) {
baton.next(result);
}
};
all_funcs[cnt_loop](baton);
cnt_loop++;
setTimeout(loop, 0);
})();
return {
end : function(callback){
end_func = callback;
}
};
};
return self;
})();
//////////////////////////////////////////////////////////
MyAsync.all(
function(baton){
...