简体   繁体   中英

Javascript / jQuery make function wait for callback before continuing

I need to know how to make a function wait for a callback from another function before executing. Below is a simplified scenario of what I am trying to accomplish.

function a(){
  b();
  // Wait for function c to callback
  var callback = function();
  // then continue function a() logic...
}
function b(){
  c();
  return false;
}

function c(){
  //trigger callback in function a
    callback();
}

Put the rest of a's logic into the callback, and if you need, use a reference to a's this

function a(){
  b();
  var that = this;
  var callback = function(){
    that.variables
    // then continue function a() logic...
  }
}
function b(){
  c();
  return false;
}

function c(){
  //trigger callback in function a
    callback();
}

What you need to do is to pass a callback to b and c as shown below and call the callback in c after its execution... assuming c is doing an async operation.

 function a() { snippet.log('inside a'); b(function() { //code that should be executed after `c` must be here... note that you cannot return a value from here to the caller of `a` snippet.log('inside callback'); }); snippet.log('after b') } function b(callback) { snippet.log('inside b'); c(callback); return false; } function c(callback) { snippet.log('inside c'); setTimeout(function() { snippet.log('inside async timeout'); //trigger callback in function a callback(); }, 100); } a(); 
 <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM