gpt4 book ai didi

javascript - Node : Dealing with Multiple Promise callbacks (Callback hell)

转载 作者:搜寻专家 更新时间:2023-10-31 23:41:08 26 4
gpt4 key购买 nike

我有 8 个相互依赖的回调。我的想法是要有一个更具可读性的过程,但我不明白如何处理这个问题。

我的回调 hell 的一个例子是:

return new Promise(function (resolve, reject) {
client.command("Command")
.then(function () {
client.command(command1)
.then(function () {
client.command(command2)
.then(function () {
client.command(command3)
.then(function () {
client.command(command4)
.then(function () {
client.command(command5)
.then(function () {
client.command(command6)
.then(function () {
client.command(command7)
.then(function () {
client.command(issue)
.then(function () {
client.command(command8)
.then(function (result) {
resolve(result.substring(0, 6));
});
});
});
});
});
});
});
});
});
});
});

有人知道如何处理吗?

最佳答案

您可以通过返回每个 promise 来拉平这个三 Angular 形,例如:

return new Promise(function(resolve, reject) {
client.command('Command')
.then(function () {
return client.command(command1);
}).then(function() {
return client.command(command2);
}).then(function(result) {
resolve(result.substring(0, 6));
});
});

编辑:您可以创建一个包含所有 promise 的数组,并在该数组上调用 Promise.each

关于javascript - Node : Dealing with Multiple Promise callbacks (Callback hell),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40224286/

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