JavaScript Asynchronous Programming Techniques: Callbacks, Promises, and Async/Await with easy and simple example

JavaScript callbacks.

A callback is a function that is passed as an argument to another function and is executed after its parent function has completed. Callbacks are commonly used in JavaScript for handling asynchronous operations, such as user input or network requests. It allows you to write code that runs after an event occurs, such as a button click or a page load. Callbacks are a fundamental concept in JavaScript and are used extensively in libraries and frameworks.
In simple words:
A callback function is a function that is passed as an argument to another function and is executed after the first function has completed. This is a common way to handle asynchronous code in JavaScript. 
Here is an example of a callback function:

   
function getData(callback) {
        // Perform some async operation
        setTimeout(() => {
            // After 1 second, execute the callback function
            callback("Data received!");
        }, 1000);
    }

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


In this example, getData is a function that performs an asynchronous operation (in this case, a timer). The callback function is passed as an argument to getData, and is executed after the asynchronous operation has completed.

JavaScript Promises.

Promises are a more advanced way of handling asynchronous operations in JavaScript. A promise represents the eventual result of an asynchronous operation. It is an object that can be in one of three states: fulfilled, rejected, or pending. Promises allow you to handle errors and results in a more elegant way and avoid callback hell.
In simple words:
JavaScript promises are an improvement over callbacks, they are a built-in feature of the JavaScript language that provides a more elegant way to handle asynchronous code. 
Here is an example of a promise:


    const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("Data received!");
    }, 1000);
    });

    promise.then(data => {
    console.log(data);
    });



In this example, promise is an instance of the Promise class, which takes a single argument, a function called the "executor", that takes two parameters, resolve and reject. The then method is used to attach a success handler that will be called when the promise is resolved.

JavaScript Async/Await.

The async keyword is used to create an asynchronous function, which returns a promise. An asynchronous function can contain an await expression, which pauses the execution of the function until the promise is fulfilled. async/await makes it easier to write asynchronous code that is more readable and less prone to errors. This feature is available in ECMAScript 2017 and later versions.
In simple words:
JavaScript Async/Await is a way to write asynchronous code that looks like synchronous code. It is built on top of promises and is a more convenient way to write asynchronous code. Here is an example of async/await:

   
async function getData() {
    const data = await new Promise((resolve, reject) => {
        setTimeout(() => {
        resolve("Data received!");
        }, 1000);
    });
    console.log(data);
    }

    getData();




In this example, the getData function is declared as async, which allows the use of the await keyword inside it. The await keyword is used before a promise and it causes the function to "pause" until the promise is resolved. In this case, the await keyword is used before the promise that is created inside the getData function. Once the promise is resolved, the value of the resolve function is assigned to the data variable, and the console.log statement is executed with the value of data.

In summary, callbacks are a way to handle asynchronous code by passing a function as an argument to another function and executing it after the first function has completed. Promises are a built-in feature of JavaScript that provides a more elegant way to handle asynchronous code, by allowing you to attach success and error handlers to a promise. Async/await is a way to write asynchronous code that looks like synchronous code, by using the async keyword to declare a function and the await keyword to "pause" the function until a promise is resolved.

I hope this helps you understand the differences between these different ways to handle asynchronous code in JavaScript and how to use them.


Mudasir Abbas Turi

Hi, this is Mudasir Abbas Turi. I am a Full-stack PHP and JavaScript developer with extensive experience in building and maintaining web applications. Skilled in both front-end and back-end development, with a strong background in PHP and JavaScript. Proficient in modern web development frameworks such as Laravel and ReactJS. Proven ability to develop and implement highly interactive user interfaces, and to integrate with various APIs and databases. Strong problem-solving skills and ability to work independently and as part of a team. Passionate about staying up-to-date with the latest technologies and industry trends.

Post a Comment

Previous Post Next Post