Skip to content Skip to sidebar Skip to footer

How Do I Refactor To Wait For The Ajax Queries To Finish Before Exporting To Csv?

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

Solution 1:

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 promisesvar 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 callbackfetchDataWeek( 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 resolveconsole.log(rows);
        exportToCsv( fileName, rows );
    })            
});

Your fetchDataWeek code then becomes:

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

Solution 2:

AJAX calls are asynchronous. Your code executes before the data is loaded. To prevent this, you should use a callback function and perform any manipulations with data loaded with AJAX there and nowhere else.

Solution 3:

If you are using JQuery a promise looks like this (using basic auth to access the endpoint, which is secured):

var url = "/myEndpoint/";       

      var req = $.ajax
      ({
        type: "GET",

        xhrFields: 
        {
          withCredentials: true
        },
        headers: 
        {
          'Authorization': 'Basic ' + btoa(gAccountName + ':' + gAccountPw)
        },
        url: url,
        dataType: 'json'
    });

    req.done(function(data)
    {
      // The data var has your results// process hereconsole.log(data);          


    });

    req.fail(function(data)
    {

      alert("There was an error loading your list of names. Please try again in a few seconds."); 
    });
  }

Post a Comment for "How Do I Refactor To Wait For The Ajax Queries To Finish Before Exporting To Csv?"