Javascript async await
Created By: chatGPT
JavaScript introduced the
async/await
syntax to simplify working with promises. This allows you to write asynchronous code that looks synchronous, which makes it easier to understand and maintain. To use async/await, you define a function using the async
keyword, and within that function, you can use the await
keyword before a promise to pause execution until the promise is resolved. Here’s how it works:async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData();
In this example, we define an asynchronous function named
fetchData
. Inside this function, we try to fetch data from an API endpoint using fetch()
, and we pause the function execution with await
until the data is retrieved. If the fetch is successful, we parse the response as JSON and log it to the console. If there’s an error, it is caught in the catch block.async function performCalculation() {
const result = await someAsyncOperation();
return result * 2;
}
performCalculation().then(result => {
console.log('Calculation result:', result);
});
You can also return values from an async function. In the example above,
performCalculation()
waits for someAsyncOperation()
to complete before returning the result multiplied by 2. After calling the function, we use .then()
to handle the result.async function main() {
const value1 = await fetchValue1();
const value2 = await fetchValue2();
processValues(value1, value2);
}
main();
When calling multiple asynchronous functions sequentially, you can use await to ensure each function completes before moving on to the next, as shown in the
main()
function above. This helps manage dependencies between asynchronous calls. For greater performance, you can parallelize them using Promise.all
.async function loadAllData() {
const [data1, data2] = await Promise.all([
fetchData1(),
fetchData2()
]);
console.log('Data1:', data1);
console.log('Data2:', data2);
}
loadAllData();
In the
loadAllData()
function, we fetch both data1
and data2
at the same time by passing them as an array to Promise.all()
. This significantly reduces our fetching time compared to waiting for each one sequentially, demonstrating how async/await can help improve performance while keeping your code clean.const fetchData = async (url) => {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return await response.json();
};