不确定为什么这不起作用。我试图嵌套一些承诺,以便我可以从playerHeader函数中获取数据。我知道getJSON是异步的,但是承诺不应该处理吗?
$.when(loadViewFunctions(),
$.Deferred(function(deferred) {
$(deferred.resolve);
})
).done(function() {
//remove
clearLoader();
});
function loadViewFunctions(){
$.when(playerHeader(function(app_data){
view_data = app_data;
}),
$.Deferred(function(deferred) {
$(deferred.resolve);
})
).done(function() {
console.log(view_data);
});
};
function playerHeader(){
$.when(
$.getJSON("/api/player_info.php?dev=1&key=56a26a18c775285f74c1879e26cceabb&player="+player_id+"",
function(player_data){
var player_bg = post_player_data[0].player_background_image;
append_data = "\
<div class='profile_header' id='profile-header' data-bg='"+player_bg+"'>\
</div>\
";
}),
$.Deferred(function(deferred) {
$(deferred.resolve);
})
).done(function() {
return append_data;
});
}
嵌套承诺是件坏事吗?
答案 0 :(得分:1)
首先也是最重要的是,我无法看到任何&#34;嵌套&#34;承诺。已经返回Promise的单个异步操作$.getJSON
- 因此,不需要$.when
/ $.Deferred
等
您的问题似乎更多是关于Promise 链接而不是嵌套
代码中的问题:
loadViewFunctions
没有回复$.when
等待的承诺,playHeader
中的同样问题,$.when
playerHeader
传递一个回调函数...... playerHeader
从不调用,$.getJSON
回调接受player_data
作为参数,但随后尝试访问post_player_data[0].player_background_image
以下是删除了冗余代码的函数,请注意完全缺少$.when
loadViewFunctions().then(clearLoader);
function loadViewFunctions(){
return playerHeader(function(app_data) {
view_data = app_data;
console.log(view_data);
});
};
function playerHeader(){
return $.getJSON("/api/player_info.php?dev=1&key=56a26a18c775285f74c1879e26cceabb&player="+player_id+"")
.then(function(player_data) {
var player_bg = post_player_data[0].player_background_image;
return "\
<div class='profile_header' id='profile-header' data-bg='"+player_bg+"'>\
</div>\
";
});
}
以上是针对现代javascript撰写的以上内容
loadViewFunctions().then(clearLoader);
function loadViewFunctions(){
return playerHeader().then(app_data => {
view_data = app_data;
console.log(view_data);
});
};
function playerHeader(){
return $.getJSON(`/api/player_info.php?dev=1&key=56a26a18c775285f74c1879e26cceabb&player=${player_id}`)
.then(player_data => `<div class='profile_header' id='profile-header' data-bg='${player_data[0].player_background_image}'></div>`);
}
编辑:意识到
view_data
是全局的,所以,loadViewFunctions
可能并不像我最初想象的那样多余