简体   繁体   English

是否总是需要使用 await 调用异步函数?

[英]Does an async function always need to be called with await?

First some context, I have an async function which logs messages on a MongoDB database.首先是一些上下文,我有一个异步函数,它在 MongoDB 数据库上记录消息。

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)
    }
}

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.一旦这个函数被触发,我就会调用“log_message”来将消息记录在我的数据库上,但我不想用等待调用它,否则,我会等到“log_message”函数返回之前处理消息减慢消息处理。

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

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

Could someone tell me whether there are some flaws in the way I intended the usage of the async/await keywords?有人能告诉我我打算使用 async/await 关键字的方式是否存在一些缺陷?

It is not necessary if your logic doesn't require the result of the async call.如果您的逻辑不需要async调用的结果,则没有必要。 Although not needed in your case, the documentation lists two benefits to having that warning enabled:尽管在您的情况下不需要,但文档列出了启用该警告的两个好处:

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.第一个是当你用 try-catch 包围你的代码时,你不会忘记添加“await”。 The second one is that having explicit 'await' helps V8 runtime to provide async stack traces第二个是明确的“await”有助于 V8 运行时提供异步堆栈跟踪

When you set async to a method, the method expects to use await inside its scope.当您将 async 设置为一个方法时,该方法期望在其范围内使用 await。 Because the functionality of async keyword is like if you were telling to the method that inside its scope there's another process which must be completed before can proceed to the method process.因为 async 关键字的功能就像你告诉方法在它的范围内有另一个必须完成的过程才能继续方法过程。

In other words, if you don't want to await to some other process to finish, then you should avoid async keyword in your method.换句话说,如果您不想等待其他某个进程完成,那么您应该避免在您的方法中使用async关键字。

Here, makes sense the await keyword:在这里, await 关键字是有意义的:

await msg.save();

Because it awaits till it's saved before log that is Done.因为它会在日志完成之前等待它被保存。 But in the methods you want all run without waiting for other processes to end.但是在您希望所有方法都运行而无需等待其他进程结束的情况下。 Just don't use asyn keyword.只是不要使用 asyn 关键字。 If you don't want to await here:如果你不想在这里等待:

await this.rs.reply(username, message, this);

Don't use async here:不要在这里使用异步:

async getReply(username, message)

If you need to await something in getReply then you should add async keyword, otherwise, is not necessary the keyword.如果您需要在getReply 中等待某些内容,那么您应该添加async关键字,否则就不需要该关键字。

每当您想等待某个操作时,您都必须将 await 与其关联,但在将 await 与其关联之前,您需要使父函数异步。

Though I see you have answers here.虽然我看到你在这里有答案。

Let me tell you the thing now!现在让我告诉你事情!

Async functions are not necessarily required to have an await call inside it, but the reason behind making a function async is that you need an asynchronous call for which you want to wait for the result before moving forward in the thread.异步函数不一定需要在其中有 await 调用,但使函数异步的原因是您需要一个异步调用,您希望在线程中前进之前等待结果。

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

The above function will work, but why exactly would you make it async?上面的函数可以工作,但是为什么要让它异步呢? Since you aren't using any asynchronous functionality.由于您没有使用任何异步功能。 It works the same if used as following:-如果按以下方式使用,它的工作原理相同:-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM