为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.安装await-auto-try-catch

npm i await-auto-try-catch

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

const AwaitAutoTryCatch = require("await-auto-try-catch");

module.exports = {
  plugins: [
    [
      AwaitAutoTryCatch, 
      { 
        exclude: [], // 默认值 []
        include: [], // 默认值 ["src"]
        printErrorInfo: true // 默认值 true
      }
    ]
  ]
};

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

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

printErrorInfo:是否打印错误信息

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

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

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

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

总结

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
async/await 配合 try/catch 是用来处理异步操作中的异常的常见做法。在 JavaScript 中,使用 async/await 可以让我们更方便地编写和管理异步代码。 下面是一个使用 async/awaittry/catch 处理异步操作异常的示例: ```javascript async function fetchData() { try { const response = await fetch('https://example.com/data'); const data = await response.json(); return data; } catch (error) { console.log('Error:', error); throw error; } } async function main() { try { const result = await fetchData(); console.log('Data:', result); } catch (error) { console.log('Error occurred:', error); } } main(); ``` 在上面的示例中,`fetchData` 函数使用 `await` 关键字等待 `fetch` 请求的响应,并使用 `await` 关键字等待响应数据的解析。如果在这些异步操作过程中发生了错误,`try/catch` 块将捕获到异常,并执行相应的错误处理逻辑。 在 `catch` 块中,我们可以记录错误信息或执行其他处理操作。如果需要将错误继续抛出,可以使用 `throw` 关键字将错误重新抛出,以便在上层的调用处再次进行错误处理。 在 `main` 函数中调用 `fetchData` 函数时,同样使用 `try/catch` 块来处理可能发生的异常。这样,我们可以更好地控制和处理异步操作的错误。 请注意,`async/await` 只是一种语法糖,它基于 Promise 实现。在使用 `async/await` 时,我们仍然需要在异步操作中处理 Promise 的状态。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值