简体   繁体   中英

async function without await keyword inside

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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