在继续

时间:2015-12-22 03:13:04

标签: javascript jquery callback

我需要知道如何在执行之前使函数等待来自另一个函数的回调。以下是我想要完成的简化方案。

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

2 个答案:

答案 0 :(得分:1)

将其余的逻辑放入回调中,如果需要,请使用对此的引用

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

答案 1 :(得分:1)

您需要做的是将回调传递给bc,如下所示,并在执行后调用c中的回调...假设c正在进行异步操作。

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>