gpt4 book ai didi

javascript - 如何防止可能的嵌套 promise ?

转载 作者:行者123 更新时间:2023-12-01 01:15:06 24 4
gpt4 key购买 nike

[不重复]问题不同,但我的问题在下面得到解答

我正在创建一个 ionic 项目,我必须在其中做出许多 promise ,然后其中一些可能会有其他 promise ,如本示例

this.Promise1()
.then((data) => {
if(logicTest){
return this.Promise2()
.then((data) => {
// ...
})
.catch(error => {
// Present error message to the user
});
}

// ...
})
.catch(error => {
// Present error message to the user
})

我看到一个例子,它把一个放在另一个下面,就像这样

this.Promise1()
.then(() => { ... })
.then(() => { ... })

但是我的例子怎么样,有时它不返回 promise ,我需要捕获不同的错误?

我什么时候做出这些嵌套的 promise ?

  • 让用户从存储中获取 API_TOKEN 以创建请求
  • 然后我请求更新销售列表中的商品
  • 然后,如果该商品的两列具有特定值,我会再次请求更新销售

最佳答案

正如您在编辑中提到的,链接您的 Promise 是解决嵌套 Promise 的经典方法。事实上,Promise API 的主要目的之一是为 "callback hell" 提供解决方案。 .

如果您想更进一步,还可以使用async/await。关于之前删除的关于async/await兼容性的答案,Ionic 使用 TypeScript,并且 TypeScript 根据配置的兼容性目标转译代码。这意味着您应该能够使用 async/await 来简化您的嵌套或链式 Promise,而不会出现任何问题。

例如:

async myFunction() {
try {
const data = await this.Promise1();
if (logicTest) {
try {
return await this.Promise2();
}
catch (error) {
// Present error message to the user
}
}

// ...
}
catch (error) {
// Present error message to the user
}
}

根据您的用例,您也许可以使用 async/await 进一步简化代码以防止过度嵌套。

如果您确实决定使用async/await,那么您应该确保阅读该功能的工作原理。滥用此功能可能会导致竞争条件和其他难以诊断的意外行为。许多博客文章和教程都比我在这里描述的功能更好。例如,快速谷歌搜索就会弹出这个:https://javascript.info/async-await .

关于javascript - 如何防止可能的嵌套 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54833830/

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