为await添加try/catch

目录

前言

babel插件的最终效果

源码:

使用步骤

总结


前言

        await可以让使用写同步代码的方式来书写异步代码,使代码看上去更整洁,如果只关心成功的情况,而不考虑失败的情况,这时候await是非常好用的。同时await不能处理失败的情况这个缺陷也体现出来了,不光如此,await修饰的是失败的promise时还会导致浏览器报错,当然我们可以使用try/catch把await包起来,这样就可以解决所有问题了。

        我不想每次写await的时候都要写try/catch,一是为了提高开发效率,二是为了代码美观。所以决定写一个babel插件来自动为await添加try/catch。


babel插件的最终效果

原始代码:

async function aa() {
    await new Promise((resolve, reject) => {
        reject({a: 123, b: 456});
    });
    if(false) {
        console.log("失败了");
    }
}
aa();

babel插件转化后的代码:

async function aa() {
    try {
        await new Promise((resolve, reject) => {
            reject({a: 123, b: 456});
        });
    } catch {
        console.log("失败了");
    }
}
aa();

源码:

const template = require('babel-template');
const catchConsole = (filePath, customLog) => `filePath: ${filePath}\n${customLog}:`;
const tryTemplate = `
    try {
    } catch (e) {
        printErrorInfo && console.log(CatchError,e);
        return;
    }
`;
function matchesFile(options, filePath) {
    let include = options.include?.length? options.include: ["src"];
    let exclude = options.exclude?.length? options.exclude: []
    let filePathArr = filePath.split("/");
    let flag = true;  // true为文件匹配, false为不匹配

    include.forEach(item => {
        if(item.includes("/")) {
            filePath.includes(item) || (flag = false);
        } else {
            filePathArr.includes(item) || (flag = false);
        }
    })

    flag && exclude.forEach(item => {
        if(item.includes("/")) {
            filePath.includes(item) && (flag = false);
        } else {
            filePathArr.includes(item) && (flag = false);
        }
    })
    return flag;
}


module.exports = function(babel) {
    let types = babel.types;
    return {
        visitor: {
            AwaitExpression(path) {
                let filePath = this.filename || this.file.opts.filename || "";
                if(path.findParent((p) => p.isTryStatement()) || !matchesFile(this.opts, filePath)) { // 判断是否在try,catch中
                    return;
                }

                let isIfStatement = path.findParent(p => p.isIfStatement());
                if(isIfStatement && path.node.end < isIfStatement.node.consequent.start) {     // 判断await是否为if的的判断条件, 应该会有更好的方法
                    return;
                }


                let awaitPath = path.findParent(p => p.isVariableDeclaration() || p.isExpressionStatement());
                let nextNode = awaitPath.getNextSibling().node;

                if(path.findParent(p => p.isVariableDeclaration())) {
                    let declarationType = awaitPath.node.kind;
                    awaitPath.node.kind = "var";

                    let declarationNode = template(`${declarationType} a = qkwvgpunrg;`)();
                    declarationNode.declarations[0].id = {...awaitPath.node.declarations[0].id};

                    awaitPath.node.declarations[0].id.type = "Identifier";
                    awaitPath.node.declarations[0].id.name = "qkwvgpunrg";
                    awaitPath.insertAfter(declarationNode);
                }

                const temp = template(tryTemplate);
                
                let tempArgumentObj = {
                    // 通过types.stringLiteral创建字符串字面量
                    CatchError: types.stringLiteral(catchConsole(filePath, "错误信息")),
                    printErrorInfo: types.booleanLiteral(this.opts.printErrorInfo)
                };

                let tryNode = temp(tempArgumentObj);

                if(nextNode?.type === "IfStatement" && nextNode?.consequent.type === "BlockStatement") {
                    tryNode.handler.body.body.unshift(...nextNode.consequent.body);
                }

                tryNode.block.body.push(awaitPath.node);
                awaitPath.replaceWith(tryNode);
                awaitPath.stop();
            }
        }
    };
};

使用步骤

1.在babel.config.js里添加如下内容

module.exports = {
  plugins: [
    [
      require("./src/lib/babel.js"), 
      { 
        exclude: [], // 默认值 []
        include: [], // 默认值 ["src"]
        printErrorInfo: false // 默认值 true
      }
    ]
  ]
};

include:自动替换的文件或文件夹组成的数组,

exclude:不自动替换的文件或文件夹组成的数组

printErrorInfo:是否打印错误信息

注意:include和exclude同时包含的文件或文件夹不自动替换

        await语句后面紧跟的if(false) {} 的代码会在await失败后执行,如果不关注await失败的情况,不需要写。

        如果await后需要立即跟一个if语句,请在await和你自己的if语句中间添加一个if(false) {}。

        目前没有更好的方式来替换if(false) {},以后有了更好的方式在进行修改。

总结

        以上就是使用babel自动为await添加try/catch的所有内容了,自己尝试一下吧。


版权声明:本文为m0_57590419原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。