javascript - 是否可以组合多个相同的 catch block ?

标签 javascript syntax ecmascript-6 promise

我想知道在 es2015 中使用 promise 链时是否可以将多个相同的 catch block 重构为一个 catch block 。

请参阅以下 promise 链(不管它做什么):

replace(replaceOptions(dirPath + '/' + jsName))
         .then((changes) => {
             fileModifiedPrint(changes);
             removeDocumentation(jsName, dirPath, dirName);
             replace(replaceHTMLID(dirPath + '/' + jsName))
                .then((changes) => {

                })
                .catch((err) => {
                    fileErrorPrint(jsName, dirPath, err, "write"); return;
                })
         })
         .catch((err) => {
             fileErrorPrint(jsName, dirPath, err, "write"); return;
         })

我可以将这两个 catch block 合并为一个吗?

最佳答案

Is it possible to combine multiple identical catch blocks?

是的,如果您通过从 .then() 处理程序中返回内部 promise 来链接您的 promise ,然后让拒绝传播冒泡到单个 .catch() block :

replace(replaceOptions(dirPath + '/' + jsName)).then((changes) => {
    fileModifiedPrint(changes);
    removeDocumentation(jsName, dirPath, dirName);

    // return this promise to chain it to the parent promise
    return replace(replaceHTMLID(dirPath + '/' + jsName)).then((changes) => {
        // do whatever you want here
    });
}).catch((err) => {
    // this will catch any rejection anywhere in the promise chain
    // that wasn't already caught by someone
    fileErrorPrint(jsName, dirPath, err, "write");
});

当您链接 promise 时,被拒绝的 promise 将传播回链中遇到的第一个 .catch() 处理程序。如果在顶层之前没有.catch() 处理程序,那么它将一直向上到那个.catch()。这允许您在本地处理拒绝并将其“隐藏”在链的其余部分,或者让它通过向上传播来拒绝整个链。您可以根据最适合您的特定情况的逻辑来实现任一类型的逻辑。


仅供引用,您也可以像这样在内部 replace() 上取消嵌套 .then():

replace(replaceOptions(dirPath + '/' + jsName)).then((changes) => {
    fileModifiedPrint(changes);
    removeDocumentation(jsName, dirPath, dirName);

    // return this promise to chain it to the parent promise
    return replace(replaceHTMLID(dirPath + '/' + jsName));
}).then((changes) => {
    // results of the second `replace()` call.
    // do whatever you want here
}).catch((err) => {
    // this will catch any rejection anywhere in the promise chain
    // that wasn't already caught by someone
    fileErrorPrint(jsName, dirPath, err, "write");
});

关于javascript - 是否可以组合多个相同的 catch block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48778349/

相关文章:

javascript - asp :XmlDataSource Expected DTD markup was not found. 第 1 行,位置 3

javascript - 如果不是位置 :absolute/fixed,则 Div 设置为后退 z-index

java - 为什么 Java 中短整数除法的结果类型不是短整数?

c++ - 带 or 表达式的 If 语句中的语法错误

javascript - 在 Node 模块 module.exports 中使用胖箭头

javascript - Node 中的阿拉伯文本编码

javascript - WebStorm 没有本地存储库

java - Java 是否允许可空类型?

node.js - 如何修复 Node 中的 ' Support for the experimental syntax ' exportDefaultFrom'当前未启用'

javascript - 如何从 `setTimeout` 回调中获取返回值?