1

I have this code

var base_url = 'http://api.zxc.loc';
var questions = []; 

function get_question(){
    if(!questions.lenght){
        $.get(base_url + '/api/questions', function(data){
            questions = data;
            console.log('get_question', questions); // GOOD, return [Object, Object ... etc ... ]
        }, 'json')
    } 
    console.log('get_question_2', questions); // BAD return empty array []

    /* var question = questions[0];
    delete questions[0];
    return question; */
}

How you can see, in $.get questions variable not empty, but after $.get, questions is empty!

Why? Thanks

Patrick Burns
  • 1,763
  • 6
  • 21
  • 35

1 Answers1

0

This is how AJAX works. In your code get_question_2 will be logged before get_question. Once an ajax call is made, the code proceeds past it (to get_question_2). Then one the ajax call is returned, the code inside your function (namely get_question) will be executed.

To summarize, the log with get_question_2 is being called as soon as the ajax call is finished being made and BEFORE the ajax call returns with the data.

Dutchie432
  • 28,798
  • 20
  • 92
  • 109