如何创建自定义回调

时间:2012-10-29 15:08:25

标签: javascript

我有一个完成一些异步操作的函数:

function funcAsynch() {
    // asynch operations
}

好吧,我想调用这个函数,并在所有异步操作完成后声明一个回调来执行。

这样的事情
customCallback(funcAsynch(), function () { 
    alert("all asynch operations are finished") 
});

我该怎么办?

3 个答案:

答案 0 :(得分:1)

funcAsynch()功能定义参数。

function funcAsynch(callback) {
    // asynch operations
    // invoke callback() when asynch is done
}

并将回调函数传递给该参数。

funcAsynch(function () { 
    alert("all asynch operations are finished");
});

答案 1 :(得分:1)

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);

答案 2 :(得分:0)

一个小帮手功能:

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");
});

只是一种方法......