DEV Community

Hastings Kondwani
Hastings Kondwani

Posted on

The basics of asynchronous JavaScript

Asynchronous JavaScript refers to the ability of JavaScript to execute code in a non-blocking way, allowing other code to run in the meantime. This is in contrast to synchronous JavaScript, which runs code in a blocking manner, where each line of code must be executed before moving on to the next.

There are several ways to implement asynchronous JavaScript, including callbacks, Promises, and async/await.

Callbacks:
A callback is a function that is passed as an argument to another function, which is then called at a later time. Here's an example of using a callback to log the result of a function:

function add(a, b, callback) {
    setTimeout(() => {
        callback(a + b);
    }, 1000);
}

add(1, 2, (result) => {
    console.log(result); // 3
})
Enter fullscreen mode Exit fullscreen mode

In this example, the add() function takes in two numbers, a and b, and a callback function. The setTimeout() function is used to simulate a delay, and after one second, the callback function is called with the result of a + b.

Promises:
Promises are a more modern way to handle asynchronous code in JavaScript. A promise represents a value that may not be available yet, but will be at some point in the future. Here's an example of using a promise to log the result of a function:

function add(a, b) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(a + b);
        }, 1000);
    });
}

add(1, 2)
    .then((result) => {
        console.log(result); // 3
    })
Enter fullscreen mode Exit fullscreen mode

In this example, the add() function returns a new promise that takes in two functions: resolve and reject. The setTimeout() function is used to simulate a delay, and after one second, the resolve() function is called with the result of a + b.

Async/await:
Async/await is a way to write asynchronous code that looks like synchronous code. It is built on top of promises and allows you to write asynchronous code using a more familiar syntax. Here's an example of using async/await to log the result of a function:

async function add(a, b) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(a + b);
        }, 1000);
    });
}

(async () => {
    const result = await add(1, 2);
    console.log(result); // 3
})()
Enter fullscreen mode Exit fullscreen mode

In this example, the add() function is declared as async and returns a promise. The await keyword is used to wait for the promise to resolve and get the result of the promise.

These are some of the basic examples of how to use callbacks, Promises, and async/await in JavaScript. Each has its own advantages and use cases, and it's important to understand the difference and choose the right one for your project.

Follow me on Linkedin: https://www.linkedin.com/in/hastings-kondwani-9b5a92200/

Top comments (0)