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.
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 );
});
Edit in response to surajck's answer:
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);
}
});
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…