Author: M Abo Bakar Aslam
async and await
Async and await are modern JavaScript features that simplify working with asynchronous code. They were introduced in ECMAScript 2017 (ES8) and provide a cleaner and more readable way to handle Promises.
An async function always returns a Promise, while the await keyword pauses execution until a Promise is resolved. This allows asynchronous code to be written in a style similar to synchronous code.
1. Basic Concept of Async and Await
asyncmakes a function return a Promiseawaitpauses execution until a Promise resolves- Helps avoid callback nesting and complex
.then()chains - Improves readability and maintainability
Note: Async and await are built on top of Promises.
2. Asynchronous Behavior Without Async/Await
Example Code 1:
- A delay is introduced using a Promise and timing function.
- JavaScript does not wait for the delay to complete.
- Execution continues immediately, leading to unexpected output order.
- Demonstrates the default asynchronous behavior of JavaScript.
// A function that simulates a delay using setTimeout
function delayExecution() {
console.log("Start..")
// Use setTimeout to pause execution for 3 seconds (3000 milliseconds)
let varProm = new Promise((resolve) => {
setTimeout(function() {
console.log("Wait for 3 seconds...")
resolve()
},
2000)
})
console.log("End after 3 seconds...")
}
// Call the function
delayExecution()3. Using Async and Await for Controlled Execution
Example Code 2:
- The function is declared using
async. - The
awaitkeyword is used before a Promise. - Execution pauses until the Promise resolves.
- Output is displayed in the intended logical order.
// An async function that simulates a delay using setTimeout
async function delayExecution() {
console.log("Start")
// Use await with setTimeout to pause execution for 2 seconds (2000 milliseconds)
let varProm = await new Promise((resolve) => {
setTimeout(function() {
console.log("Wait")
resolve()
}, 2000)
})
console.log("End after 2 seconds")
}
// Call the async function
delayExecution()4. Fetching Data Using Async/Await
Example Code 3:
- Data is fetched from an external source using an asynchronous request.
awaitis used to wait for the response.- The response is converted into usable format.
- Error handling is managed using
try...catch.
// An async function to fetch data from a URL
async function fetchAndDisplayData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1'); // Replace with your desired URL
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json(); // Parse the response as JSON
console.log(data);
} catch (error) {
console.error(error);
}
}
// Call the async function to fetch and display data
fetchAndDisplayData();5. File Handling Using Async/Await
Example Code 4:
- A file is read asynchronously using modern Promise-based APIs.
awaitensures the file content is retrieved before proceeding.- Errors are handled gracefully using
try...catch. - Provides a cleaner alternative to callback-based file handling.
const fs = require('fs').promises
// An async function to read a text file
async function readTextFile() {
try {
const data = await fs.readFile('example.txt', 'utf-8')
console.log(data)
} catch (error) {
console.error('Error reading the file:', error)
}
}
// Call the async function to read the text file
readTextFile()6. Key Advantages
- Makes asynchronous code easier to read
- Eliminates complex chaining of
.then() - Provides structured error handling using
try...catch - Improves debugging and maintainability
7. Important Notes
awaitcan only be used inside anasyncfunction- Async functions always return a Promise
- If a value is returned, it is automatically wrapped in a Promise
- Errors inside async functions should be handled using
try...catch