在导出为CSV之前,我该如何重构以等待AJAX查询完成? [英] How do I refactor to wait for the AJAX queries to finish before exporting to CSV?
问题描述
我的以下代码是通过单击按钮触发的.当我运行它时,将创建CSV,但它是空的. console.log(rows)
输出与预期的一样,但有一个注释,说明Value below was evaluated just now.
I have the code below triggered by button click. When I run it, the CSV is created but is empty. The console.log(rows)
output is as expected, but has a note saying Value below was evaluated just now.
如何让exportToCsv
的执行等到AJAX调用完成?
How do I make the execution of exportToCsv
wait until the AJAX calls are complete?
$("#downloadBtn").click(function() {
weeks = getWeeks(startDate.val(), endDate.val());
// start downloading the data
for (i=0; i< weeks.length; i++) {
// contains $.ajax query that appends to "rows"
fetchDataWeek( weeks[i][0], weeks[i][1] );
}
console.log(rows);
exportToCsv( fileName, rows );
});
编辑以响应 surajck的答案:
除了使用Promises
的建议代码外,我还对fetchDataWeek
函数进行了如下编辑,但是运行时我得到了Uncaught TypeError: Promise resolver undefined is not a function
.
In addition to the suggested code using Promises
, I've edited my fetchDataWeek
function as follows, but when I run it I get Uncaught TypeError: Promise resolver undefined is not a function
.
function fetchDataWeek( startDay, endDay ) {
startDay = makeDateString(startDay);
endDay = makeDateString(endDay);
url = "https://api" + startDay + endDay + ".json";
$.ajax({
url: url,
success: function(result){
parseHistory(result);
_promise.resolve(result);
}
});
}
推荐答案
以下是一些通用代码可以帮助您理解:
Here is some generic code to help you understand:
$("#downloadBtn").click(function() {
weeks = getWeeks(startDate.val(), endDate.val());
// start downloading the data
// Create an array to hold all your promises
var promiseArray = [];
for (i=0; i< weeks.length; i++) {
// contains $.ajax query that appends to "rows"
var _promise = Q.defer(); // Create a promise (using https://github.com/kriskowal/q)
// send this promise to the ajax callback
fetchDataWeek( weeks[i][0], weeks[i][1], _promise );
promiseArray.push(_promise) // Push this promise into the array
}
Promise.all(promiseArray).then( function () { // Wait for all promises to resolve
console.log(rows);
exportToCsv( fileName, rows );
})
});
您的fetchDataWeek
代码随后变为:
function fetchDataWeek( startDay, endDay, _promise ) {
startDay = makeDateString(startDay);
endDay = makeDateString(endDay);
url = "https://api" + startDay + endDay + ".json";
$.ajax({
url: url,
success: function(result){
parseHistory(result);
_promise.resolve(result); // resolving that promise here
},
error: function (error) {
_promise.reject(error) // rejecting it in case of error
}
});
}
这篇关于在导出为CSV之前,我该如何重构以等待AJAX查询完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!