0

The stuff I don´t understand I find it rather long to explain so please bear with me. I have the following incude js in my page:

var include = (function(){
    var exports = {}
    var test = function(url){
        var result = [];
        $.ajax(url).then(function(data){
            result = data.form.records;  // assume data.form.records valid
            console.log(result) // displays correctly Array [Object,Object] 
        });
        return result;
    }
    exports.test = test;
    return exports
})();

then from the page i make the following call (assum that some_url is valid)

var array = include.test(some_url);

later i have a event ( some button click ) that will use the values in the array

input.on('click',function(){
   console.log(array) // 2
});

My problem is that when the event occurs the array variable is still VOID , The console.log // 2 displays Array [ ]....

i know my test function returns immediately so the immediate value of array variable is Array [ ] , but by the time the input.click gets called , the then() callback would already have been executed so the array itself should be modified .After all array is a reference ...

Any suggestion ? I don´t usually ask questions because most of the time i find the answers by searching but i already tried for a day. Maybe i have a lack of inspiration. Some help would be appreciated

jonny
  • 3,022
  • 1
  • 17
  • 30
  • 1
    you need to set the array inside the callback function (then(... ) –  Apr 05 '16 at 08:10
  • Yeah, K3N is right, AJAX is asynch, return is synch the way you coded it, doesn't really work using both asynch and synch. – Clemens Himmer Apr 05 '16 at 08:12
  • Just wondering if it's really that hard to indent your code properly and put semicolons where they belonw. –  Apr 05 '16 at 08:35

1 Answers1

0

array is referring to an empty array, but in the ajax callback you have result = data.form.records; which is assigning a new array to result instead of updating the array referred by array that is why even after the console logs the correct value for result array is referring to the initial empty array.

var include = (function() {
  var exports = {}
  var test = function(url) {
    var result = [];
    $.ajax(url).then(function(data) {
      result.length = 0;//remove existing items from the array
      result.push.apply(result, data.form.records);//copy the items from the records to the result array instead of assigning a new value
      console.log(result) // displays correctly Array [Object,Object] 
    });
    return result;
  }
  exports.test = test;
  return exports
})();
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • I have changed references and didn't even noticed it ... thank you for showing me that result = data.form.records; was the error i had in my code – Gabriel Ion Apr 05 '16 at 10:28