Skip to content Skip to sidebar Skip to footer

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. async function log_message(sender, conversationId, text) { try { const msg = new

Solution 1:

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:

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

Solution 2:

When you set async to a method, the method expects to use await inside its scope. 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.

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.

Here, makes sense the await keyword:

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. 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.

Solution 3:

Whenever you want to await some operation you have to associate await with that but before associate await with that you need to make parent function async.

Solution 4:

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.

asyncgetReply(username, message) {
        log_message("user", username, message);
        console.log("HI");
        let reply = awaitthis.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 = awaitthis.rs.reply(username, message, this);
        return reply;
    }

Post a Comment for "Does An Async Function Always Need To Be Called With Await?"