0

im using CI3 and jquery and i need to execute the getFechas(val) function not asynchronous .. so this is my code

 $('#datepicker1').on('change', function() {

    $.when(getFechas($('#datepicker1').val())).done(function(a1){
     fechas = a1;
     //console.log($('#datepicker1').val());
      console.log(a1);
     console.log(a1.slice());
    });

});

and the ajax function

function getFechas(val){   
var venc =[];
 $.ajax({
    type: "POST",
    url: base_url+"index.php/admin/ajax_call/saldos",
    data: {fecha: val},
    success: function (data) {

        var i =1;
        $.each(data, function (key, value) {

            venc[i] = value.fecha_vencimiento;
            // console.log(value.fecha_vencimiento);

            // console.log(value.comuna_id + ':' + value.comuna_nombre);
            i++;

        });

    }

   });
        return venc;
}

I need to access to the array venc[] ....the return value of function ... and copy the value on fechas var (fechas is global empty array )

Lifu Huang
  • 11,930
  • 14
  • 55
  • 77
lpz
  • 65
  • 1
  • 8
  • If a function calls an asynchronous function then it cannot be synchronous. If you want a function to be synchronous then it cannot make an asynchronous call. – Felix Kling Apr 16 '17 at 01:15

1 Answers1

1

You can't return venc from getFechas. Ajax is asynchronous .

Return the $.ajax() promise and when it resolves your $.when will resolve.


Simplified version to allow running demo:

function getFechas(val) {
  // return promise
  return $.ajax({
    type: "POST",
    url: '...',
    data: {....}
  }).then(function(resp) {
    // return processed data to next then() in chain
    var venc = resp.map(function(item) {
      return item.fecha_vencimiento
    });    
    return venc;
  });
}

$.when(getFechas( /*datepickerValue*/ )).done(function(venc) {
  console.log(venc);
}).fail(function(err){
   console.log('Request failed');
});

DEMO

Reference: How do I return the response from an asynchronous call

Community
  • 1
  • 1
charlietfl
  • 170,828
  • 13
  • 121
  • 150