What are Asynchronous Functions?

One of the key features of JavaScript is its ability to execute code asynchronously, which means that it can run multiple pieces of code at the same time without blocking the execution of other code because as you already know JS is single-threaded. This is very useful when dealing with tasks such as making requests to a server or reading and writing to a file because usually you won’t get an immediate response and you would need to wait for the data to return.

Async functions in JavaScript are a way to write asynchronous code using a synchronous syntax. They are created using the “async” keyword and are made up of “await” expressions, which pause the execution of the async function until a Promise is resolved.

Here is an example of an “async” function that makes a request to a server and logs the response:

async function getData() {
  const response = await fetch('https://example.com/data');
  const data = await response.json();
  console.log(data);
}

In this example, the “fetch” function returns a Promise that resolves with a response object. The await keyword is used to pause the execution of the async function until the Promise is resolved. The “response.json” function also returns a Promise, so the await keyword is used again to pause the execution until the data is returned and then you can do whatever you need to do with the data.

Async functions can be combined with other asynchronous patterns, such as “Promises” and “async/await”. They can also be used with “try/catch” blocks to deal with potential issues that may occur during the execution of your script.

I will write more about asynchronous functions in the future since this is meant to be an introduction to them but, in summary, async functions provide a convenient way to wait for data and process it once you get the response. They can be a headache at the beginning but once you use them enough, they will become second nature.

I hope you found this useful, feel free to leave a comment since it could help other people better understand async functions.

Also if you are getting started in your journey of learning programming read my article “The Best Way to Learn Programming“.

1 thought on “What are Asynchronous Functions?

  1. Pingback: How to use Async Await - Kevin Skayro Blog

Comments are closed.