DEV Community

Cover image for Asynchronous JS
Devi
Devi

Posted on • Edited on

1

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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay