3 Minutes with Kent

Is it okay to make a function async if it doesn't need to be async?

02.09.2021 - By Kent C. DoddsPlay

Download our free app to listen on your phone

Download on the App StoreGet it on Google Play

Hey friends so I got a question on discord from somebody who asked

effectively is it okay to put async away on a function that doesn't need it

and you can get useless rules that will prevent this. I think I have the

enabled because I don't typically want to do this but there are situations

sometimes where you want to start with an API that isn't asynchronous now

but you're pretty confident that it's going to be asynchronous in the

future and it's just easier.

To plan with that asynchrony from the get-go rather than try to retrofit

everything to work with asynchrony in the future and so yes, it's I think

it's acceptable and it's okay to make something async when it doesn't need

to be and you just have to be aware that any consumer is going to have to

consume an async API rather than a synchronous one and you'll have to

consider the fact that because it's async it it is like as soon as you

attach that async keyword onto the function onto the function keyword like

right in front of that function keyword or in front of theParentheses if

you're doing an arrow function whatever as soon as you put that async

keyword on there it immediately means that no matter what the function does

it's returning a promise and the any consuming code cannot proceed until

the next tick of the event loop, you know, I'm talking about like if the

consuming code is using async away if it's using promises with dot then

then the the success handler of that promise is going to run on the next

tick of the event loop and so that means that just has some interesting

implications around you know closures andStillness and but in in practice

that's not normally going to be too much of an issue so I would say that

yeah it's okay to put async on a function that doesn't need it but I

wouldn't do it for no reason so like there would need to be an explanation

and in a code base where you have coworkers who are going to look at this

code and and even yourself who's going to look at this code in the future,

it would be useful for you to write a code comment to explain why you're

doing this so that people don't remove it and then accidentally break some

consuming code because you're not using type script, for example.

If you're using textcript then you know, maybe it's okay, but anyway, I

hope that is useful to you and I hope that you had a marvelous day in that

or that you're going to whenever this is, you know, good afternoon good

evening tonight. Truman shows now and I'll talk to you later bye.

More episodes from 3 Minutes with Kent