gpt4 book ai didi

javascript - 如何重构以等待 AJAX 查询完成后再导出到 CSV?

转载 作者:行者123 更新时间:2023-12-03 04:47:15 27 4
gpt4 key购买 nike

我有通过单击按钮触发的以下代码。当我运行它时,CSV 已创建但为空。 console.log(rows) 输出符合预期,但有一条注释说明 下面的值刚刚被评估。

如何让 exportToCsv 的执行等到 AJAX 调用完成为止?

$("#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's answer :

除了使用 Promises 的建议代码之外,我还按如下方式编辑了 fetchDataWeek 函数,但是当我运行它时,出现了 Uncaught TypeError: Promise解析器未定义不是一个函数

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);
}
});
}

最佳答案

这里有一些通用代码可以帮助您理解:

$("#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
}
});
}

关于javascript - 如何重构以等待 AJAX 查询完成后再导出到 CSV?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42817690/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com