如何防止可能的嵌套承诺?

How to prevent POSSIBLE nested promises?

[没有重复] 问题不同,但我的问题在下面得到了回答

我正在创建一个离子项目,我必须在其中做很多承诺,其中一些可能会有像这个例子这样的其他承诺

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(() => { ... })

但是我的示例有时没有 return 承诺,我需要捕获不同的错误?

我什么时候做出这些嵌套承诺?

正如您在编辑中提到的,链接您的 promise 是处理嵌套 promise 的经典方式。事实上,Promise API 的主要目的之一是为 "callback hell".

提供解决方案

如果您想更进一步,您还可以使用 async/await。关于先前删除的关于 async/await 兼容性的回答,Ionic 使用 TypeScript,TypeScript 根据配置的兼容性目标转译代码。这意味着您应该能够使用 async/await 来毫无问题地简化您的嵌套或链式承诺。

例如:

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,那么您一定要仔细阅读该功能的工作原理。滥用此功能会导致竞争条件和其他难以诊断的意外行为。许多博客文章和教程比我在这里更好地描述了功能。快速 Google 搜索弹出了这个,例如:https://javascript.info/async-await.