-1

My js code needs to wait until ajax is finished to load the data.

if (district_search_value[0] == true) {
        var zone_search_value = checkZone(district_search_value[1], datas[i]['recipient_zone']);
        console.log(zone_search_value);
    }

The checkZone function :

   function checkZone(district_id, zone_name) {
    var value = [];
    value[0] = false;
    value[1] = 0;
    find_zones_from_district_id().then(function(data) {
        // Run this when your request was successful
        console.log(data);
        var zones = JSON.parse(data);
            //console.log(zones);
            for (zones_row = 0; zones_row < zones.length; zones_row++) {
                if (zone_name == zones[zones_row]['zone_name']) {
                    value[0] = true;
                    value[1] = zones[zones_row]['id'];
                }
            }
        return value;
    }).catch(function(err) {
        // Run this when promise was rejected via reject()
        console.log(err);
    })
}

The main promise function :

function find_zones_from_district_id(district_id) {
    return new Promise(function (resolve, reject) {
        $.ajax({
            type: 'POST',
            url: 'ajaxData_for_user.php',
            data: {import_excel_find_zones_from_district_id: 'district_id'},
            success: function (data) {
                resolve(data) // Resolve promise and go to then()
            },
            error: function (err) {
                reject(err) // Reject the promise and go to catch()
            }
        });
    });

}

What is the reason behind javascript not waiting for promise to resolve ? I've also tried the $.when in jquery but this also does not wait for ajax to load data.

iamneaz
  • 11
  • 5

1 Answers1

0

Two things need fixing, a third thing is optional

  1. Wait for the promise to resolve before logging results using .then()

    if (district_search_value[0] == true) {
      checkZone(district_search_value[1], datas[I]['recipient_zone'])
      .then(zone_search_value => {
        console.log(zone_search_value);
      }
    }
    
  2. checkZone must return the promise it gets from find_zones_from_district_id

    function checkZone(district_id, zone_name) {
      var value = [];
      value[0] = false;
      value[1] = 0;
      return find_zones_from_district_id().then(function(data) {
        // ...
    
  3. As a commenter points out, there's no need to wrap the ajax call...

    function find_zones_from_district_id(district_id) {
      return $.ajax({
        type: 'POST',
        url: 'ajaxData_for_user.php',
        data: {import_excel_find_zones_from_district_id: 'district_id'} // did you want to pass a string here or district_id parameter?
      })
    }
    
danh
  • 62,181
  • 10
  • 95
  • 136
  • thank you for your answer. I've applied all three changes. Now i'm getting this error `find_zones_from_district_id(...).then(...).catch is not a function` in the checkZone function. This is the code `find_zones_from_district_id(district_id).then(function (data) { ` – iamneaz Jun 21 '20 at 14:22
  • @iamneaz, I think this is due to jquery Ajax promises returning their own sort of promise. Try `.fail(function(error) {})`. (see https://api.jquery.com/jQuery.ajax/) – danh Jun 21 '20 at 14:36
  • @iamneaz if you did the third step and directly returned the ajax call note the ajax() returns [jQuery's own structure jqxhr](https://api.jquery.com/jQuery.ajax/#jqXHR) object, not a true Promise it won't have a catch() method. Use `.fail()` instead or use the second argument to `then()` to set an error callback, eg `.then(function(){}, function(){/*error callback*/})` – Patrick Evans Jun 21 '20 at 14:42