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

Note: Async and await are built on top of Promises.

2. Asynchronous Behavior Without Async/Await

Example Code 1:

// 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:

// 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:

// 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:

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

7. Important Notes