确定是否完成了2个AJAX进程,即使其余的AJAX进程仍在进行中


Identify if 2 AJAX process is done even if remaining AJAX Processes is still on progress

我已经知道如何检测所有AJAX进程是否由下面的代码完成:

jQuery(document).ajaxStop(function(){
    alert('All AJAX Process is done.');
}); 

例如有三个AJAX进程:oneProcess, twoProcess, threeProcess

oneProcesstwoProcess已经完成,threeProcess还在加工中。我是如何调用这两个AJAX进程的?

最简单的方法是使用$.when(),传递oneProcess, twoProcess作为参数。

var oneProcess = new $.Deferred(function(dfd) {
  setTimeout(function() {
    dfd.resolve("oneProcess complete")
  }, Math.floor(Math.random() * 1500));
  return dfd.promise()
}).then(log);
var twoProcess = new $.Deferred(function(dfd) {
  setTimeout(function() {
    dfd.resolve("twoProcess complete")
  }, Math.floor(Math.random() * 1500));
  return dfd.promise()
}).then(log);
var threeProcess = function(msg) {
  log(msg);
  return new $.Deferred(function(dfd) {
    setTimeout(function() {
      dfd.resolve("threeProcess complete")
    }, Math.floor(Math.random() * 1500));
    return dfd.promise()
  })
}
function log(msg) {
  console.log(msg);
}
var checkOneTwo = $.when(oneProcess, twoProcess);
checkOneTwo.then(function(one, two) {
  threeProcess(
    "oneProcess state:" + oneProcess.state()
    + ", twoProcess state:" + twoProcess.state()
  ).then(log)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

或者你可以利用setInterval在每个延迟对象上调用.state()来检查oneProcess, twoProcessdeferred.state()调用是否返回"resolved"

var oneProcess = new $.Deferred(function(dfd) {
  setTimeout(function() {
    dfd.resolve("oneProcess complete")
  }, Math.floor(Math.random() * 1500));
  return dfd.promise()
}).then(log);
var twoProcess = new $.Deferred(function(dfd) {
  setTimeout(function() {
    dfd.resolve("twoProcess complete")
  }, Math.floor(Math.random() * 1500));
  return dfd.promise()
}).then(log);
var threeProcess = function(msg) {
  log(msg);
  return new $.Deferred(function(dfd) {
    setTimeout(function() {
      dfd.resolve("threeProcess complete")
    }, Math.floor(Math.random() * 1500));
    return dfd.promise()
  })
}
function log(msg) {
  console.log(msg);
}
var interval = null;
var checkOneTwo = function() {
  var oneTwo = new $.Deferred();
  interval = setInterval(function() {
    console.log(oneProcess.state() === "resolved"
                , twoProcess.state() === "resolved");
    if (oneProcess.state() === "resolved" &&
        twoProcess.state() === "resolved") {
          clearInterval(interval);
          oneTwo.resolve()
    }
  }, 100);
  return oneTwo.promise().then(function() {
    return threeProcess(
      `oneProcess state:${oneProcess.state()}`
      + `twoProcess state:${twoProcess.state()}`
    )
  })
}
checkOneTwo().then(log);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>