是否总是需要使用 await 调用异步函数? [英] Does an async function always need to be called with await?

查看:49
本文介绍了是否总是需要使用 await 调用异步函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先是一些上下文,我有一个异步函数,用于在 MongoDB 数据库上记录消息.

First some context, I have an async function which logs messages on a MongoDB database.

async function log_message(sender, conversationId, text) {
    try {
        const msg = new Message({
            sender: sender,
            conversationId: conversationId,
            text: text
        });
        await msg.save();
        console.log("Done");
    } catch (e) {
        console.log("An error happened while logging the message: " + e)
    }
}

现在,我有另一个异步函数,它在我收到消息时被触发并负责处理它并获取一些数据.一旦这个函数被触发,我就会调用log_message"来将消息记录在我的数据库上,但我不想用等待调用它,否则,我会等到log_message"函数返回之前处理消息减慢消息处理.

Now, I have another async function that gets triggered when I receive a message and takes care of processing it and fetching some data. As soon as this function get triggered I call "log_message" to log the message on my database, but I do not want to call it with await, otherwise, I would wait until the "log_message" function returns before processing the message slowing down the message processing.

    async getReply(username, message) {
        log_message("user", username, message);
        console.log("HI");
        let reply = await this.rs.reply(username, message, this);
        return reply;
    }

尽管如此,Jetbrains Webstorm 给了我这个警告缺少等待异步函数调用".现在,我做了一些测试,如果我在没有 await 的情况下调用该函数,系统会按照我的预期运行,消息会得到处理,我的日志记录函数会在不中断的情况下异步将数据写入数据库.如果相反,我在调用日志函数之前放置了 await 关键字,则主函数中的代码的执行将暂停,直到数据库尚未写入.

Nevertheless, Jetbrains Webstorm gives me this warning "Missing await for an async function call". Now, I did some tests and if I call the function without await the system behaves as I expect, the message gets processed and my logging function writes the data on the db asynchronously without interrupting. If instead, I put the await keyword before calling the logging function the execution of the code in the main function gets suspended until the db has not been written.

有人能告诉我,我打算使用 async/await 关键字的方式是否有缺陷?

Could someone tell me whether there are some flaws in the way I intended the usage of the async/await keywords?

推荐答案

如果您的逻辑不需要 async 调用的结果,则没有必要.尽管在您的情况下不需要,文档列出了启用该警告的两个好处:

It is not necessary if your logic doesn't require the result of the async call. Although not needed in your case, the documentation lists two benefits to having that warning enabled:

虽然这通常不是必需的,但它有两个主要好处.第一个是当你用 try-catch 包围你的代码时,你不会忘记添加await".第二个是明确的await"有助于 V8 运行时提供异步堆栈跟踪

While this is generally not necessary, it gives two main benefits. The first one is that you won't forget to add 'await' when surrounding your code with try-catch. The second one is that having explicit 'await' helps V8 runtime to provide async stack traces

这篇关于是否总是需要使用 await 调用异步函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆