我正在开发一个大量使用Javascript和jQuery的Web应用程序.
我基本上app在网页加载并init()在页脚中调用方法时创建一个对象.
var app = new App();
app.init();
Run Code Online (Sandbox Code Playgroud)
这些是方法中的第一行代码init().
// Load up the index
app.loadIndex();
alert(hashtag_index);
Run Code Online (Sandbox Code Playgroud)
这些是该loadIndex()方法的几行.
hashtag_index = [];
// Load the Topic JSON File
$.ajax({
url : './data/index.json',
type : 'GET',
dataType : 'json',
.
.
.
// If the file loading is successful, save the index data
success : function(data){
var raw_index = [];
$.each(data, function(key, val) {
raw_index.push(data[key]);
});
// Add the hashtag object to global hashtag_index
hashtag_index = raw_index;
}
});
Run Code Online (Sandbox Code Playgroud)
基本上该loadIndex()方法所做的是加载一个大约135kb的json文件,并将数据作为对象加载到hashtag_index变量中.该hashtag_index变量定义的全局,所以它的全局访问.
变量hashtag索引有8个不同的Object数组.但是当我尝试alert()变量时,变量尚未初始化.
但alert()只返回空白消息.当我将此作为消息返回时:
alert(typeof(hashtag_index))
Run Code Online (Sandbox Code Playgroud)
我收到undefined了消息.
但现在我确定变量已加载,因为当我通过谷歌Chrome控制台访问变量时,我可以看到变量已加载并且所有对象都在那里.
唯一是我通过使用这行代码解决了问题:
// Load up the index
app.loadIndex();
setTimeout( function(){
alert(hashtag_index);
}, 500);
Run Code Online (Sandbox Code Playgroud)
通过让javascript睡眠500毫秒,我已经有足够的时间来加载它.
当然我已经尝试了以下解决方案,但没有一个成功:
解决方案1 :(进入无限循环)
// Load up the index
app.loadIndex();
while(!hashtag_index.length > 0) {
continue;
};
alert(hashtag_index);
Run Code Online (Sandbox Code Playgroud)
解决方案2 :(进入无限循环)
// Load up the index
app.loadIndex();
while(hashtag_index.length == 0) {
continue;
};
alert(hashtag_index);
Run Code Online (Sandbox Code Playgroud)
解决方案3 :(进入无限循环)
// Load up the index
app.loadIndex();
while(typeof hashtag_index === 'undefined') {
continue;
};
alert(hashtag_index);
Run Code Online (Sandbox Code Playgroud)
解决方案4:*(进入无限循环)
// Load up the index
app.loadIndex();
while(typeof hashtag_index == null) {
continue;
};
alert(hashtag_index);
Run Code Online (Sandbox Code Playgroud)
现在我的问题是如何在不引起任何未来问题的情况下解决这个问题.我试图解决以前的解决方案的问题,但没有一个成功正确.
您的app.loadIndex();方法使用ajax,它是异步的.因此,alert(hashtag_index);在ajax调用完成之前执行并处理结果.
更改您的代码以使用回调,或(我的偏好)app.loadIndex();返回一个promise对象.
以下是您实现承诺的方式:
var loadIndex = function() {
var def = $.Deferred();
$.ajax({
//...
success: function(result) {
// do whatever
def.resolve();
}
//...
});
return def.promise();
};
Run Code Online (Sandbox Code Playgroud)
....
// Load up the index
app.loadIndex().done(function() {
alert(hashtag_index);
});
Run Code Online (Sandbox Code Playgroud)
您可能需要对此进行扩展以init()返回承诺或接受"已完成"回调,具体取决于您的使用情况.
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |