Consider a javascript function that is essentially a wrapper for another async function. Should that wrapping function necessarily be async itself, even if it does need need to await the underlying promise?
Here's a simple example:
function myWrapperFunction() {
console.log('Calling myAsyncFunction')
return myAsyncFunction();
}
async function myAsyncFunction() {
const url = 'URL'
const data = await fetch(url)
return JSON.parse(data)
}
Should myWrapperFunction
be async
? I would guess it doesn't need to be given that it just returns the promise from myAsyncFunction
. However the first example in the correct code section of es-lint's no-return-await
rule hints otherwise: https://eslint.org/docs/rules/no-return-await
Thanks!
I'd write it like that:
function myWrapperFunction() {
console.log('Calling myAsyncFunction')
const promise = myAsyncFunction();
return promise;
}
to improve maintainability of the code. Eg to ensure other people wouldn't need to ask themselves whether returning a Promise is intentional or not.
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.