gpt4 book ai didi

javascript - 如何在重试 Ajax 场景中消除这种丑陋的重复代码?

转载 作者:行者123 更新时间:2023-11-28 20:39:40 26 4
gpt4 key购买 nike

由于 getGamesByPlayerId 的回调调用性质(恰好是 Ajax 调用),我似乎无法弄清楚如何消除以下重复代码:

// Load the player's games.
gc.api.getGamesByPlayerId(gc.game.player.id, gc.game.player.access_token, function(data) {

if(data.status_code === 401) {

// Call may have failed due to being called too fast. Retry...
gc.api.getGamesByPlayerId(gc.game.player.id, gc.game.player.access_token, function(data) {

if(data.status_code === 401) {

// Call may have failed due to being called too fast. Retry...
gc.api.getGamesByPlayerId(gc.game.player.id, gc.game.player.access_token, function(data) {

if(data.status_code === 401) {

// Call may have failed due to being called too fast. Retry...
gc.api.getGamesByPlayerId(gc.game.player.id, gc.game.player.access_token, function(data) {

if(data.status_code === 401) {

// OK. It's safe to assume the server is current, and that
// we truly are not authorized to do this.
alert("You are not authorized.");

} else {

// Add games to HTML.
for( var i = 0; i < data.length; i++ ) {

var html = '<li><a href="?g=' + data[i].id + '">' + data[i].id + '</a></li>';

$('#games').append(html);

}

}

});

} else {

// Add games to HTML.
for( var i = 0; i < data.length; i++ ) {

var html = '<li><a href="?g=' + data[i].id + '">' + data[i].id + '</a></li>';

$('#games').append(html);

}

}

});

} else {

// Add games to HTML.
for( var i = 0; i < data.length; i++ ) {

var html = '<li><a href="?g=' + data[i].id + '">' + data[i].id + '</a></li>';

$('#games').append(html);

}

}

});

} else {

// Add games to HTML.
for( var i = 0; i < data.length; i++ ) {

var html = '<li><a href="?g=' + data[i].id + '">' + data[i].id + '</a></li>';

$('#games').append(html);

}

}

});

通常,我会考虑使用 for 循环,但这行不通,因为我不想快速连续地触发 Ajax 调用。我希望仅当前面的调用失败时才触发重试。

最佳答案

忽略您需要连续多次发出相同请求的情况,您可能可以使用递归函数来完成此任务。例如,类似:

loadPlayerGames(4);

function loadPlayerGames(triesLeft) {
gc.api.getGamesByPlayerId(gc.game.player.id, gc.game.player.access_token, function(data) {
if(data.status_code !== 401) {
// Add games to HTML.
for( var i = 0; i < data.length; i++ ) {
var html = '<li><a href="?g=' + data[i].id + '">' + data[i].id + '</a></li>';
$('#games').append(html);
}
} else if(triesLeft <= 0) {
// OK. It's safe to assume the server is current, and that
// we truly are not authorized to do this.
alert("You are not authorized.");
} else {
// Call may have failed due to being called too fast. Retry...
loadPlayerGames(triesLeft - 1);
}
});
}

关于javascript - 如何在重试 Ajax 场景中消除这种丑陋的重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14637412/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com