我有一个完成一些异步操作的函数:
function funcAsynch() {
// asynch operations
}
好吧,我想调用这个函数,并声明一个回调以在所有异步操作完成时执行。
像
customCallback(funcAsynch(), function () {
alert("all asynch operations are finished")
});
我该怎么做?
我有一个完成一些异步操作的函数:
function funcAsynch() {
// asynch operations
}
好吧,我想调用这个函数,并声明一个回调以在所有异步操作完成时执行。
像
customCallback(funcAsynch(), function () {
alert("all asynch operations are finished")
});
我该怎么做?
funcAsynch()
为您的函数定义一个参数。
function funcAsynch(callback) {
// asynch operations
// invoke callback() when asynch is done
}
并将回调函数传递给该参数。
funcAsynch(function () {
alert("all asynch operations are finished");
});
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);
一个小辅助函数:
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");
});
只有一种方法...