gpt4 book ai didi

javascript - 如何用async/await解决厄运金字塔?

转载 作者:行者123 更新时间:2023-11-30 09:20:03 25 4
gpt4 key购买 nike

我想知道如何避免这段代码的厄运金字塔:

原始代码

var PlayerService = {
getPlayerTeamId: function(playerId, callback) {
$.ajax({
url: "/player/" + playerId + "/team",
success: function(team) {
callback(team.id)
}
});
},
getPlayers: function(teamId, callback) {
$.ajax({
url: "/team/" + teamId + "/player",
success: callback
});
}
};

var PlayerDetailsController = {
playerId: 8,
showTeammatesClick: function() {
PlayerService.getPlayerTeamId(this.playerId, function(teamId) {
PlayerService.getPlayers(teamId, function(playerList) {
// Render playerList
});
});
}
};

这是我使用 async/await 的版本,以避免 sol 金字塔:我的版本

var PlayerService = {
getPlayerTeamId: async function(playerId, callback) {
return await $.ajax({
url: "/player/" + playerId + "/team",
success: function(team) {
callback(team.id)
}
});
},
getPlayers: async function(teamId, callback) {
return await $.ajax({
url: "/team/" + teamId + "/player",
success: callback
});
}
};

var PlayerDetailsController = {
playerId: 8,
showTeammatesClick: function() {
PlayerService.getPlayerTeamId(this.playerId, function(teamId) {
PlayerService.getPlayers(teamId, function(playerList) {
// Render playerList
});
});
}
};

可以吗?或者我如何正确使用这个异步/等待?我正在尝试“getPlayerTeamId”和“getPlayers”不应期望回调参数,并以任何方式避免回调。

有什么建议吗?谢谢,祝你有美好的一天:D

最佳答案

末日金字塔不是通过在某处放置 async/await 来解决的,而是通过返回和链接 promise 来解决,而不是接受回调。请注意,当您的服务方法只需返回一个 promise 时,它们甚至不需要异步 - 无论如何 don't use return await :

const PlayerService = {
getPlayerTeamId(playerId ) {
// ^ no callback
return $.ajax({
// ^^^^^^ the promise
url: "/player/" + playerId + "/team"
}).then(team => team.id);
},
// same here
getPlayers(teamId) {
return $.ajax({
url: "/team/" + teamId + "/player"
});
}
};

现在 promisification完成后,我们可以在调用这些方法时开始使用 Promise .then()await 语法来代替嵌套回调:

const PlayerDetailsController = {
playerId: 8,
async showTeammatesClick() {
const teamId = await PlayerService.getPlayerTeamId(this.playerId);
const playerList = await PlayerService.getPlayers(teamId);
… // Render playerList
}
};

关于javascript - 如何用async/await解决厄运金字塔?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52332256/

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