gpt4 book ai didi

javascript - 如何在 JavaScript 的异步 Promise 中使用同步?

转载 作者:行者123 更新时间:2023-11-30 11:08:59 24 4
gpt4 key购买 nike

当我运行以下代码时:

b = async attempt => {
if (attempt == 5) {
return;
}
console.log("Starting attempt:", attempt);
b(attempt + 1).then(() => {
console.log("Finished attempt:", attempt);
});
};
b(0);

输出是:

Starting attempt: 0
Starting attempt: 1
Starting attempt: 2
Starting attempt: 3
Starting attempt: 4
Finished attempt: 4
Finished attempt: 3
Finished attempt: 2
Finished attempt: 1
Finished attempt: 0

但是,我想在每次递归调用之前调用另一个 promise a,如下所示:

a = Promise.resolve();
b = async attempt => {
if (attempt == 5) {
return;
}
console.log("Starting attempt:", attempt);
a.then(() => {
b(attempt + 1);
}).then(() => {
console.log("Finished attempt:", attempt);
});
};
b(0);

现在的输出是:

Starting attempt: 0
Starting attempt: 1
Starting attempt: 2
Finished attempt: 0
Starting attempt: 3
Finished attempt: 1
Starting attempt: 4
Finished attempt: 2
Finished attempt: 3
Finished attempt: 4

如何修改第二个代码块以确保输出与第一个代码块相同?

最佳答案

您不返回内部 promise a.then(() => {b(attempt + 1);}) 就破坏了 promise 链。添加返回语句应该有所帮助。

此外,我建议不要将 async/await 语法与 .then 和回调混合使用。

下面的代码看起来更“同步”并且可以解决问题。

const a = Promise.resolve();
const b = async attempt => {
if (attempt == 5) {
return;
}
console.log("Starting attempt:", attempt);

await a

await b(attempt + 1)

console.log(`Finished attempt: ${attempt}`)
};

b(0);

关于javascript - 如何在 JavaScript 的异步 Promise 中使用同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54506668/

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