0

I would like to retrieve a variable outside an anonymous function, At the moment, I have this :

function recupererFichier(callback, params){
    $.ajax({
        url : 'map.php',
        dataType: 'json',
        success: function (data) {
            //console.log(data)
            callback(data, params);
        }
    });
}

function test() {
var recup = [];

    recupererFichier(
        function (data, params) {
            console.log(recup)
            console.log("data", data.length);
            for (var i = 0; i < data.length; i++){
                recup[i] = data[i];
            }

            console.log(recup) //["breche_de_roland_.gpx", "casque_lheris_.gpx", "col_d_arrious.gpx", "lac_combales.gpx", "lac_d_isabe_.gpx", "lac_de_gaube_.gpx", "lac_de_pombie_.gpx", "pic_midi_de_bigorre.gpx", "refuge_lac_migouelous.gpx", "refuge_wallon.gpx", "tour_des_lacs_-_lac_d_ayous_.gpx"]
        });

    //Retrieve array here
    console.log(recup) //undefined
}

I want to get the array generated, outside the anonymous function. That is possible ? Thanks

simonmnt
  • 59
  • 11
  • 1
    Declare the variable outside of the function and you can reference it. – pendo May 17 '17 at 13:50
  • It's not about returning the value (and scope). It's about asynchronous call. The value of `recup` will be modified only in the next 'tick' - after AJAX request will be completed. The linked thread describes possible approaches to this problem. – raina77ow May 17 '17 at 13:50
  • prometize your recupererFichier – F.bernal May 17 '17 at 13:52
  • @pendo The primary reason why global variables are discouraged in javascript is because, in javascript all code share a single global namespace, also javascript has implied global variables ie. variables which are not explicitly declared in local scope are automatically added to global namespace. Relying too much on global variables can result in collisions between various scripts on the same page... http://stackoverflow.com/questions/2613310/ive-heard-global-variables-are-bad-what-alternative-solution-should-i-use – F.bernal May 17 '17 at 13:59

0 Answers0