DEV Community

Cover image for Asynchronous JS
Devi
Devi

Posted on • Edited on

Asynchronous JS

JavaScript is synchornous single threaded language.
But, We can acheive Asynchornous operation using following 3 methods

1.Callback
2.Promises
3.Async await

1. Callbacks
A callback is a function passed as an argument to another function, which is then executed inside the outer function to complete some kind of routine or action.

function fetchData(callback) {
    setTimeout(() => {
        callback('Data fetched');
    }, 1000);
}

function displayData(data) {
    console.log(data);
}

fetchData(displayData);
Enter fullscreen mode Exit fullscreen mode

In this example, fetchData simulates an asynchronous operation using setTimeout. Once the data is “fetched,” it calls the displayData function.

2. Promises
Promises provide a more robust way to handle asynchronous operations. A Promise represents a value that may be available now, or in the future, or never.

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Data fetched');
        }, 1000);
    });
}

fetchData()
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error(error);
    });
Enter fullscreen mode Exit fullscreen mode

Here, fetchData returns a Promise that resolves after 1 second.The then method is used to handle the resolved value, and catch handles any errors.

3. Async/Await
Async/Await is syntactic sugar built on top of Promises, making asynchronous code look and behave more like synchronous code.async

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Data fetched');
        }, 1000);
    });
}

async function displayData() {
    try {
        const data = await fetchData();
        console.log(data);
    } catch (error) {
        console.error(error);
    }
}

displayData();
Enter fullscreen mode Exit fullscreen mode

In this example, fetchData returns a Promise, and displayData uses the await keyword to wait for the Promise to resolve. The try/catch block is used to handle any errors.

Top comments (0)