我想要並行調用兩個函數說功能a()
和功能b()
。這些功能是相互獨立的,可以說執行這兩個功能所需的時間並不固定。有時功能a()
比功能b()
需要更多的時間,反之亦然。但是還有另一個功能c()
,只有當功能a()
和b()
完成時才應執行。在javascript中異步執行函數
我應該如何使用jQuery的Deferred對象來做到這一點?
我想要並行調用兩個函數說功能a()
和功能b()
。這些功能是相互獨立的,可以說執行這兩個功能所需的時間並不固定。有時功能a()
比功能b()
需要更多的時間,反之亦然。但是還有另一個功能c()
,只有當功能a()
和b()
完成時才應執行。在javascript中異步執行函數
我應該如何使用jQuery的Deferred對象來做到這一點?
要達到此目的,您可以使a()
和b()
函數返回延遲對象,一旦它們的邏輯完成,就會返回延遲對象。一旦前面的功能完成,您就可以運行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>
不能以193k用戶競爭......我是回答太慢了:( –
您可以使用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
});
閱讀有關此文件我會使用一個全局變量來determ的操作狀態和(如果你需要或每毫秒)執行輪詢每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>
這是不完全的問題的答案。我不使用延期或類似的東西。
但我想顯示一些我經常做的事情:添加一個onReady回調函數作爲參數()和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();
}
});
});
https://stackoverflow.com/questions/15018931/jquery-custom-deferred-functions檢查出來 – jack