How to use async & await in JavaScript
Unlock the Power of Asynchronous JavaScript 🚀
- What are Async/Await?
- Why Async/Await is Essential in JavaScript Development 💪
- A Foundation for Asynchronous JavaScript ⚙️
- How to Effectively Use Promises in Your Code 🌟
- What to Focus on for Effective Async/Await Usage 🎯
- Where Async/Await Shines in Real-world Applications ✨
- Let's fetch data with Async/Await 🌐
async/await
is one of the most used feature in JavaScript which is specially used to simplify work with asynchronous code and make it super easier
to write and understand the code. It is literally built on top of Promises and provides a more readable, clean and synchronous-looking syntax
for handling asynchronous operations. here in this article we are going to be learning the way how we can use the Async & Await concepts in JavaScripts and where to use them. literally Almost everything there can be about Async & Await We are going to be learning in this article.
Where to use Async & Await?
async/await is primarily used in JavaScript to simplify asynchronous operations, providing a more readable and synchronous-style syntax when working with Promises and asynchronous code. It finds application in various scenarios, such as making API calls and fetching data using libraries like fetch, Axios, or XMLHttpRequest, working with functions or libraries that return Promises for cleaner code, handling file operations with the File API or Node.js file system operations, interacting with databases (e.g., Mongoose for MongoDB or Sequelize for SQL databases) in a more synchronous-looking manner, creating asynchronous code with timers and delays (e.g., setTimeout), and dealing with multiple concurrent Promises using Promise.all or similar methods in combination with await. async/await enhances code organization and is especially valuable when waiting for one asynchronous task's completion before starting another or managing error handling in asynchronous code.
Let's use Async & Await.
Here Whenever we have to work with Async we literllay have to define the Async function like following:
Defining an async
Function:
You can easily create an async
function by prefixing a function declaration or expression with the
async
keyword. An async
function always returns a Promise implicitly.
async function fetchData() {
// Asynchronous code here
}
Using await
Inside an async
Function:
Inside an async
function, you can use the await
keyword before an expression that
returns a Promise. The await
keyword pauses the execution of the function until the Promise is
resolved or rejected. This allows you to write asynchronous code in a more linear, synchronous-style manner.
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}
In this example, await
is used with the fetch
function to retrieve data from a
remote server. The code will wait for the fetch
Promise to resolve before moving on to parsing
the JSON response.
Handling Errors:
To handle errors in an async
function, you can use try...catch
blocks as shown in
the example above. If an error occurs in any await
-ed Promise, it will be caught and processed
in the catch
block.
Fetching Data with Async & Await
Now that all you have learnt how to use all these concepts, we are tending to fetch the data with following code you can see:
Fetching data using an async
function in JavaScript is a common use case when you need to make HTTP
requests to external APIs or retrieve data from a server. You can use the fetch
API in combination with
async/await
to simplify the process. Here's an example of how to fetch data using an async
function:
async function fetchData() {
try {
// Make an HTTP GET request using the fetch API
const response = await fetch('https://api.example.com/data');
// Check if the response status is OK (HTTP status code 200)
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Parse the response body as JSON
const data = await response.json();
// Do something with the data
console.log('Data:', data);
// Return the data if needed
return data;
} catch (error) {
console.error('Error:', error);
}
}
// Call the async function to fetch data
fetchData();
In this example:
We define an async
function named fetchData
that encapsulates the process of making
an HTTP GET request to 'https://api.example.com/data'
.
Inside the function, we use await
with fetch
to send the request asynchronously.
fetch
returns a Promise that resolves to the response from the server.
We check if the response status is OK (HTTP status code 200). If it's not OK, we throw an error to handle potential network issues.
We use await
again to parse the response body as JSON. The response.json()
method
also returns a Promise that resolves to the parsed JSON data.
We log the retrieved data to the console or perform any other necessary processing or whatever you want you can do with it like you can print all the Data in an HTML element.
Ultimately, we call the fetchData
function to initiate the data retrieval or you can simply call the function using a click of button
This code demonstrates how to use an async
function to fetch data from a remote server, handle errors,
and process the retrieved data in JSON form. Remember that the URL 'https://api.example.com/data'
is provided here should be replaced with the actual API
endpoint you want to fetch data from. You can use any URL that includes data. There are many APIs you can use for.
Using Async & Await with different kind of functions other than the "fetch"
Using async/await
with Promises:
You can also use async/await
with other Promises, not just with built-in functions like
fetch
. Here's an example with a custom Promise:
async function getData() {
try {
const result = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data fetched successfully');
}, 1000);
});
console.log(result);
} catch (error) {
console.error('Error:', error);
}
}
In this case, the await
keyword is used with a custom Promise that resolves after a delay.
Using async/await
in a Non-async Function:
You can use async/await
inside non-async functions by calling the async function and using
.then()
to handle the result. For example:
function processData() {
fetchData() // Assuming fetchData is an async function
.then(data => {
console.log('Data:', data);
})
.catch(error => {
console.error('Error:', error);
});
}
Here, fetchData()
is an async function, but processData()
is not. However, we can
still use Promises to work with the asynchronous result.
Top-level await
(Node.js 14+):
In Node.js 14 and later, you can use top-level await
in module scripts, which means you can use
await
outside of async functions at the top level of your module. This simplifies startup code
in certain cases.
// Node.js 14+ module script
import fetchData from './fetchData.js';
async function main() {
const data = await fetchData();
console.log('Data:', data);
}
main();
In this example, await
is used at the top level of the module, making it easier to work with
asynchronous operations in module initialization code.
Remember that async/await
is a powerful tool for working with asynchronous operations in JavaScript, but
it's essential to understand how Promises work as well since async/await
is built on top of them.