【发布时间】:2019-12-05 20:23:12
【问题描述】:
我有 2 个函数,doFirst() 和 doSomethingElse()。现在第一个函数由大约 10 个 AJAX 请求组成,这些请求在检查该过滤器是否被选中的条件下执行。这些 AJAX 请求与 URL 通信,并在各自的数组中保存一组 ID。完成此操作后,必须触发 doSomethingElse() 来绘制结果表。在这一点上,我通过设置超时来执行它们。我想知道一种更好的方法来等待函数完成然后执行下一个函数。任何帮助是极大的赞赏。 谢谢!
//How I am currently calling the functions:
doFirst();
doSomethingElse();
function doFirst(){
var filterArrayTaxSel1 = $("#taxIA span").get().map(el => el.textContent);
for (var i = 0; i < filterArrayTaxSel1.length; i++) {
filterArrayTaxSel1[i] = filterArrayTaxSel1[i].replace(" ", "%20");
}
// taxgroup2 - Selector
queryBuilder = filterArrayTaxSel1;
//console.log(queryBuilder);
console.log(filterArrayTaxSel1);
if (filterArrayTaxSel1.length > 0) {
if (filterArrayTaxSel1.length > 0 && filterArrayTaxSel1[0] != "All") {
console.log("I am inside the IF!");
for (var i = 0; i < filterArrayTaxSel1.length; i++) {
var baseURL = "some URL here";
console.log(baseURL);
responses(baseURL);
function responses(baseURL) {
$.ajax({
url: baseURL,
type: "get",
cache: false,
headers: {
'Content-Type': 'application/json'
},
success: function (data) {
console.log(data.features.length);
for (var i = 0; i < data.features.length; i++) {
if (taxArrayT1.indexOf(data.features[i].properties.taxon_id) == -1) {
taxArrayT1.push(data.features[i].properties.taxon_id);
}
}
console.log("In the Invertebrate Animals Section 1");
console.log(taxArrayT1.length);
}
})
}
}
}
else if (filterArrayTaxSel1[0] == "All") {
console.log("I am inside the IF!");
var baseURL = "some URL here";
console.log(baseURL);
responses(baseURL);
function responses(baseURL) {
$.ajax({
url: baseURL,
type: "get",
cache: false,
headers: {
'Content-Type': 'application/json'
},
success: function (data) {
console.log("I am inside the ELSE IF ALLL!");
console.log(data.features.length);
for (var i = 0; i < data.features.length; i++) {
if (taxArrayT1.indexOf(data.features[i].properties.taxon_id) == -1) {
taxArrayT1.push(data.features[i].properties.taxon_id);
}
}
console.log("In the Invertebrate Animals Section 2");
console.log(taxArrayT1.length);
}
})
}
}
//Selection 1 Tax Group AJAX Call Sensitivity ARRAY WITH 0 to Multiple CASES - ENDS.
}
//some more AJAX Calls depending on whether the filter exists
//End of function
}
function doSomethingElse(){
//Code to draw the Table using the arrays from the previous function
}
【问题讨论】:
-
你能分享你的代码吗?
-
你使用的是纯javascript还是一些库?大多数库返回 Promise 对象,它使您能够链接调用(从第二个开始,仅在第一个完成时)
-
@smartilabs 我正在使用纯 JavaScript 进行编码。不使用任何库。我不完全确定如何使用这些承诺对象。你也可以举个例子吗?
-
@Azhr-M 我刚刚发布了一个示例代码。抱歉开头草率。
-
使用
$.when()
标签: javascript jquery html ajax asynchronous