0

I always thought async functions need to contain "await" keyword inside, for example:

async function doTask() {
 let total = await CustomFunction(values);
 console.log(`Main Total: ${total}`);
}
doTask();

But I also saw some like that define async function without having await as:

GetData = async ( method, url, params) =>
{
    Axios.request({
        method, url, params
    });
}

so what's the point to have async keyword added in front of a function that doesn't have "await" keyword?

  • Because you can now `await` *that* function. It's impossible to have every single async function containing `await`, as they have to `await` *something*. If every single one just `awaits` and is hence `async`, then where is the original function that they all use `await` for? – VLAZ Nov 28 '19 at 06:46
  • duplicate of https://stackoverflow.com/questions/45594596/async-function-without-await-in-javascript all the answers posted here are copied from here – Sasi Kumar M Nov 28 '19 at 06:48
  • Does this answer your question? [Async function without await in Javascript](https://stackoverflow.com/questions/45594596/async-function-without-await-in-javascript) – Sasi Kumar M Nov 28 '19 at 06:51
  • It’s also not unlikely that the person who wrote this code didn’t know what `async` really does. – Felix Kling Nov 28 '19 at 07:39

3 Answers3

0

Well in your example it probably is a bug; I guess there should be a return await in front of Axios.request.

But in general, unless the caller explicitly only accepts functions returning a Promise, there is no point in declaring an await-less function async.

Jonas Berlin
  • 3,344
  • 1
  • 27
  • 33
0

In simple word if you use await in front of any async function it will keep waiting for request to success.

For in your example :

async function doTask() {
 let total = await CustomFunction(values);
 console.log(`Main Total: ${total}`);
 return total;
}
doTask();

In above example if you call doTask() then total will contains the result of request. But if you don't use await then total may not contains result of request.

async function doTask() {
 let total = CustomFunction(values);
 console.log(`Main Total: ${total}`);
 return total;
}
doTask();

Now, If you call doTask() then it will may return undefined or null instead of actual request.

Kishan Bharda
  • 5,446
  • 3
  • 30
  • 57
0

Marking function as async but without await inside is a bad practice because it forces your transpiling tool (babel/typescript) to add some additional code to resulting bundle.
See example with typescript, try to remove/add async word.
But code without await will work synchronously as Juhil Somaiya said.

nickbullock
  • 6,424
  • 9
  • 27