Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何创建自定义回调_Javascript - Fatal编程技术网

Javascript 如何创建自定义回调

Javascript 如何创建自定义回调,javascript,Javascript,我有一个函数可以执行一些异步操作: function funcAsynch() { // asynch operations } 我想调用这个函数,并声明一个回调,在所有异步操作完成后执行 比如 customCallback(funcAsynch(), function () { alert("all asynch operations are finished") }); 如何操作?为funcAsynch()函数定义一个参数 function funcAsynch(ca

我有一个函数可以执行一些异步操作:

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

只有一种方法

function F() {
    var async = asyncFn();

    async.ready(function() {
        // Called when emitReady is called
    });

    async.emitReady();
}
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");
});