我想知道在 es2015 中使用 promise 链时是否可以将多个相同的 catch 块重构为单个 catch 块。
请参阅以下承诺链(不管它做什么):
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 块合二为一吗?
是否可以组合多个相同的 catch 块?
是的,如果您通过从.then()
处理程序中返回内部承诺来链接承诺,然后让拒绝传播冒泡到单个.catch()
块,则可以:
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");
});
当您链接承诺时,被拒绝的承诺将传播回链,到达.catch()
它遇到的链中的第一个处理程序。如果.catch()
在顶层之前没有处理程序,那么它会一直到那个.catch()
. 这允许您在本地处理拒绝并将其从链的其余部分“隐藏”,或者通过让它向上传播来拒绝整个链。您可以根据最适合您的特定情况的逻辑来实施任一类型的逻辑。
仅供参考,您也可以像这样.then()
在内部取消嵌套replace()
:
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");
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句