Content


Synchronous vs Asynchronous JavaScript

//Synchronous example
console.log("Start");
console.log("Middle");
console.log("End");

//Asynchronous example
console.log("Start");
setTimeout(() => {
    console.log("Async Task");
}, 2000);
console.log("End");

Callbacks

Example : Callback Function
function fetchData(callback) {

    //Simulating an asynchronous task using setTimeout
    setTimeout(() => {

        //Calling the callback function after 2 seconds
        callback("Data received");

    }, 2000);
}

//Passing a function as a callback
fetchData((message) => {
    console.log(message);
});
Explanation of the Example

In this example, the callback ensures that the code inside it runs only after the asynchronous task is completed.

Callbacks were widely used before Promises. However, using many nested callbacks can make code difficult to read and maintain. This situation is known as callback hell, which is why modern JavaScript prefers Promises and async/await.


Promises

Promise States
Example : Creating a Promise
const getData = new Promise((resolve, reject) => {

    //Simulating success or failure
    let success = true;

    if (success) {
        //Promise completed successfully
        resolve("Data loaded successfully");
    } else {
        //Promise failed
        reject("Error loading data");
    }
});
Explanation of the Example
What Problem Do Promises Solve?

Promises provide a structured way to handle asynchronous operations, which is why modern JavaScript and React applications rely on them.


then() and catch()

getData
    .then(response => {
        console.log(response);
    })
    .catch(error => {
        console.log(error);
    });

async and await

async function loadData() {
    const message = await getData;
    console.log(message);
}

loadData();

Error Handling using try...catch

async function loadData() {
    try {
        const result = await getData;
        console.log(result);
    } catch (error) {
        console.log("Error:", error);
    }
}

fetch() API

fetch("https://jsonplaceholder.typicode.com/users")
    .then(response => response.json())
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.log(error);
    });

HTTP Methods Overview

Method Purpose
GET Fetch data
POST Create new data
PUT Update existing data
DELETE Remove data

Handling API Response Data

async function getUsers() {
    const response = await fetch("https://jsonplaceholder.typicode.com/users");
    const users = await response.json();
    console.log(users);
}

Loading and Error State Concept

let isLoading = true;
let error = null;

fetch("https://jsonplaceholder.typicode.com/users")
    .then(res => res.json())
    .then(data => {
        isLoading = false;
        console.log(data);
    })
    .catch(err => {
        isLoading = false;
        error = err;
        console.log("Error occurred");
    });