我有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
}
答案 0 :(得分:1)
Promise
只是一个对象,您可以向其传递一些可以完成某些工作的函数,完成后它将调用一个回调函数,您可以将其用于进一步的操作。
您可以在以下位置找到完整的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/prototype
例如,您有一个函数,该函数返回Promise对象:
function makeAjaxCall(url, methodType){
var promiseObj = new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
if (xhr.status === 200){
console.log("xhr done successfully");
var resp = xhr.responseText;
var respJson = JSON.parse(resp);
resolve(respJson);
} else {
reject(xhr.status);
console.log("xhr failed");
}
} else {
console.log("xhr processing going on");
}
}
console.log("request sent succesfully");
});
return promiseObj;
}
然后您进行多个ajax调用:
let promise1 = makeAjaxCall(URL1, "GET");
let promise2 = makeAjaxCall(URL2, "GET");
let promise3 = makeAjaxCall(URL2, "GET");
然后您有一个“监听器”,它等待所有诺言(ajax调用)完成:
Promise.all([promise1, promise2, promise3]).then(function(values) {
console.log(values);
});
您有很多关于该主题的文章和文档:
答案 1 :(得分:1)
Promise对象代表最终的完成(或失败) 异步操作及其结果值。
这是一个示例,说明如何使用Promise
对象使异步代码(例如AJAX请求)更易于处理。 Promise.all
似乎是解决问题的理想之选。您可以执行以下操作:
const doFirst = () => {
console.log('Making AJAX requests, please wait..');
const asyncActions = [
//Wrap all your async code in a Promise
new Promise((resolve, reject) => {
//Resolve some phony data as part of our AJAX request simulation
setTimeout(() => resolve({
name: 'Item 1',
id: 1
}), 1000)
}),
new Promise((resolve, reject) => {
setTimeout(() => resolve({
name: 'Item 2',
id: 2
}), 4000)
}),
Promise.resolve({
name: 'Item 3',
id: 3
})
];
//Since all your async actions are stored in a iterable, we can use
return Promise.all(asyncActions);
}
const doSomethingElse = values => {
console.log('Here is the data returned from our AJAX requests:');
values.forEach(value => {
console.log(`Name: ${value.name} || ID: ${value.id}`)
});
}
doFirst().then(doSomethingElse);
答案 2 :(得分:-1)
在您的代码中,您正在使用jQuery,因此您可以利用其一些内置方法。您基本上希望跟踪阵列中的所有Ajax调用,因此当您进行Ajax调用时,请将它们推入阵列中。然后,您可以使用jQuery的$.when()
完成所有步骤后再执行下一步。
基本思路:
function firstStep() {
var requests = []
var list = [1,2,3]
for (var i = 0; i < list.length; i++) {
requests.push($.ajax(...));
}
return requests
}
function secondStep() {
console.log(arguments)
}
var requests = firstStep()
$.when.apply(undefined, requests).then(secondStep)
如果您不使用jQuery,则可以使用promise.all