ちょっとしたヘルパー関数:
function asyncFn() {
var readyList = [],
isReady = false;
function emitReady() {
isReady = true;
var i = 0,
len = readyList.length;
for ( ; i < len; i++ ) {
emit( readyList[i] );
}
}
function emit( fn ) {
fn();
}
function ready( fn ) {
if ( !isReady ) {
readyList.push( fn );
}
else {
emit( fn );
}
}
return {
ready: ready,
emitReady: emitReady
};
}
ユースケース1
function F() {
var async = asyncFn();
async.ready(function() {
// Called when emitReady is called
});
async.emitReady();
}
ユースケース2
function customAsync() {
var async = asyncFn();
/*
Async stuff going on here....
*/
setTimeout(function() {
async.emitReady();
}, 500);
return async;
}
function customCallback(def, callback) {
def.ready(callback);
}
customCallback(customAsync(), function() {
console.log("async is operated");
});
たった1つのアプローチ...