Reputation: 47945
I have a function that done some asynch operations :
function funcAsynch() {
// asynch operations
}
well, I'd like calling this function, and declare a callback to execute when all asynch operations are finished.
Somethings like
customCallback(funcAsynch(), function () {
alert("all asynch operations are finished")
});
how can I do it?
Upvotes: 1
Views: 124
Reputation: 48761
Define a parameter for your funcAsynch()
function.
function funcAsynch(callback) {
// asynch operations
// invoke callback() when asynch is done
}
And pass the callback function to that parameter.
funcAsynch(function () {
alert("all asynch operations are finished");
});
Upvotes: 1
Reputation: 47099
A little helper function:
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
};
}
Usecase 1
function F() {
var async = asyncFn();
async.ready(function() {
// Called when emitReady is called
});
async.emitReady();
}
Usecase 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");
});
Just one approach...
Upvotes: 0
Reputation: 10953
function doSomething(callback) {
// ...
// Call the callback
callback('stuff', 'goes', 'here');
}
function foo(a, b, c) {
// I'm the callback
alert(a + " " + b + " " + c);
}
doSomething(foo);
Upvotes: 1