Creating An Async TypeScript Function
September 06, 2021
I think asynchronous behavior in JavaScript and TypeScript (or any language) is intimidating to many developers. Even though it’s been around a long time now. Maybe it’s because we, as humans, typically digest information one line at a time. It somehow feels like we’re not in control when it comes to async operations. Something happening in the background will another thing is happening somewhere else.
With that in mind I thought it might be fun to try and create the most basic async TypeScript function I could think of that was still useful. Below is what I came up with, a simple method that uses fetch
to make an asynchronous GET request to a given url.
const fetchUrl = async (url: string): Promise<Response> => {
return await fetch(url)
}
const res: Response = await fetchUrl("http://example.com")
console.log(res.ok)
The idea here is that I’m creating an asynchronous function called fetchUrl
that will eventually return a Response
object via a Promise
. A Promise is a contract that The function is asynchronous because I’ve added the async
keyword in front of it and I’m “awaiting” the response from the fetch
call.
Later, when I call the function, I wait for the response to come back before the code can proceeed past the const res ...
line. The console.log
or any code after it will not be executed until the fetchUrl
method has finished. Finished, meaning completed the http request even if it failed. A failure is still a completion.
The fetchUrl
could throw an error for any number of reasons. Including not being able to make the request e.g: bad network. An improvement to the above could would be to wrap the const res ...
in a try/catch block. This would ensure that the code doesn’t error out with an unresolved Promise error.
...
try {
const res: Response = await fetchUrl('http://example.com');
console.log(res.ok);
} catch (error) {
console.log(error);
}
The async
and await
keywords are wonderful. Gone are the days of callback functions. Even then usage is becoming less and less common. It seems like everyone is moving towards async/await
adoptation. From the MDN docs:
The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.