1

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?

3 Answers 3

1

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");
});
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.