2016-12-05 75 views
0

编辑:我的js代码涉及异步,因此它实际完成init()完成执行前的ready方法中的第二个alert()。任何想法如何确保我的第二个alert()在init()之后执行?先谢谢你。由于异步,Js代码不会按顺序运行

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); 
} 
+3

JavaScript是单线程的。你的代码是无效的(有语法错误),所以我们不能告诉你实际发生了什么。你可能也已经减少了你的例子太多。您的代码可能包含一些异步部分。这个问题可能有助于了解发生了什么的一般想法:http://stackoverflow.com/q/14220321/218196。 –

+2

'做一些可能需要时间的事情 - 听起来像它甚至可能是异步的 –

+0

谢谢你指出。它是异步的。 – vkosyj

回答

0

使用承诺

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);