javascript 中函数的异步执行

Asynchronous execution of functions in javascript

我想并行调用两个函数,比如函数 a() 和函数 b()。这两个函数是相互独立的,可以说执行这两个函数所需的时间是不固定的。有时函数 a() 比函数 b() 花费更多时间,反之亦然。但是还有另一个函数 c() 应该只在函数 a()b() 都完成时执行。

我应该如何使用 jQuery 的 Deferred 对象执行此操作?

要实现此目的,您可以使 a()b() 函数 return 延迟对象,一旦它们的逻辑完成,您就可以 resolve() 延迟对象。一旦之前的两个功能都完成,您就可以 运行 c() 。试试这个:

function a() {
  var aDef = $.Deferred();
  setTimeout(function() {
    aDef.resolve('a done');
  }, 1000);
  return aDef;
}

function b() {
  var bDef = $.Deferred();
  setTimeout(function() {
    bDef.resolve('b done');
  }, 3000);
  return bDef;
}

function c() {
  console.log('all done!')
}

console.log('running...');
$.when(a(), b()).done(function(a, b) {
  console.log(a);
  console.log(b);
  c();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

您可以使用 jQuery.when() 来执行此操作。请在 https://api.jquery.com/jquery.when/

阅读有关此内容的文档
a = function () {
//your code for function a
}
b = function () {
//your code for function b
}

$.when( a(), b() ).done(function c() {
    //your code for function c
});

我会使用一个全局变量来确定运行状态并每 100 毫秒(或者如果需要的话每毫秒)执行一次轮询。

var myStatus = {
  "a": false,
  "b": false
};

function a() {
  myStatus["a"] = true;
  console.log(myStatus['a']);
}

function b() {
  myStatus["b"] = true;
}

function getStatusText() {
  var s = 'not complete';
  if (myStatus.a && myStatus.b) {
    s = 'all complete';
  } else {
    if (myStatus.a) {
      s = 'a complete';
    }
    if (myStatus.b) {
      s = 'b complete';
    }
  }
  return s;
}

function c() {
  //check operational status
  var statusText = getStatusText();
  document.getElementById('status').innerHTML = statusText;
}
setInterval(
  function() {
    c()
  }, 100);
<button onclick="a()">Set a() complete</button><button onclick="b()">Set b() complete</button>

<p>operational status <span id="status"></span></p>

请参考Jquery defer 和 promise 方法来处理调用。

https://api.jquery.com/deferred.promise/

https://api.jquery.com/promise/

这不完全是问题的答案。我不使用延迟或类似的东西。

但我想展示我经常做的事情:添加一个 onReady 回调,作为 a() 和 b() 的参数。我将这些回调添加到任何需要时间执行的自写函数中。

function a(onready) {
  // let's say we get Ajax data
  $.ajax({
    url: 'data.php',
    success: function(data) {
      $('#message').html(data);
      if(typeof onready == 'function') {
        onready();   // you might also want to add message as a parameter, like onready(data), or anready('Data okay'), ...
      }
    }
  });
}

function b(onready) {
  // let's say we sort <table> rows
  sortTable('my_table', 'my_row', 'ASC');  // this function (not provided here) is not asynchronous, it just takes time before it's done
  if(typeof onready == 'function') {
    onready();   
  }
}

function c() {
  alert('Yippy!');
}

$(document).ready(function() {  // or this could be after the client clicks on a button, or so
  var aReady = false;
  var bReady = false;

  a(function() {
    aReady = true;
    if(aReady && bReady) {
      c();
    }
  });

  b(function() {
    bReady = true;
    if(aReady && bReady) {
      c();
    }
  });

});