0

EDIT: My js code involve asynchronous, so that it actually finishes the second alert() in the ready method before the init() finish executing. Any idea on how to make sure that my second alert() executes after the init()? Thank you in advance.

var notes = [];    
$(document).ready(function() {
    //var notes = [];
    alert("before " + notes.length);
    init();
    alert("after " + notes.length)
    //execute(notes, 0);

});


function init() {
    loadJSON(function(response) {
    // Parse JSON string into object
    var actual_JSON = JSON.parse(response);
    var len = actual_JSON.notes.length;
    //alert("length is " + len);

    for(var i = 0; i < 6; i++) {
        notes.push(actual_JSON.notes[i]);
    }
    //alert("after for loop " + notes.length);


});
}

function loadJSON(callback) {   

    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'test.json', true); 
    xobj.onreadystatechange = function () {
    if (xobj.readyState == 4 && xobj.status == "200") {
        callback(xobj.responseText);
    }
};
    xobj.send(null);  
}   
vkosyj
  • 757
  • 1
  • 7
  • 21
  • 3
    JavaScript is single threaded. Your code is invalid (has syntax errors), so we can't tell you what actually happens. You probably also have reduced your example too much. Your code likely contains some asynchronous parts. This question might help to get a general idea about what's going on: http://stackoverflow.com/q/14220321/218196 . – Felix Kling Dec 05 '16 at 04:47
  • 2
    `do something that might take time` - sounds like it could even be asynchronous – Jaromanda X Dec 05 '16 at 04:49
  • Thank you for pointing out. It is asynchronous. – vkosyj Dec 05 '16 at 04:56

1 Answers1

0

Use promise

var notes = [];    
$(document).ready(function() {
    alert("before " + notes.length);
    init()
    .then(function(){
        alert("after " + notes.length)
    })
    .catch(function(err){
        console.log('error in init()', err)
    });
});


function init() {
  return new Promise(function(resolve, reject) {
     loadJSON(function(response) {

        var actual_JSON = JSON.parse(response);
        var len = actual_JSON.notes.length;

        for(var i = 0; i < 6; i++) {
            notes.push(actual_JSON.notes[i]);
        }

        resolve()
     });
  });
}

function loadJSON(callback) {   
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'test.json', true); 
    xobj.onreadystatechange = function () {
    if (xobj.readyState == 4 && xobj.status == "200") {
        callback(xobj.responseText);
    }
};
    xobj.send(null);  
Gaurav joshi
  • 1,743
  • 1
  • 14
  • 28