我想知道在 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/