What are the ways to make the code Asynchronous?

What are the ways to make the code Asynchronous?

Welcome Reader!

Let's explore the ways to make the javascript synchronous code to turn into asynchronous code.

Here are some techniques used to achieve synchrony in code:

Callbacks: A function(callback) which is passed to another function as an argument, which then executes the callback once a certain task is completed.

function greet(name, callback) {
    console.log('Hello, ' + name + '!');
    callback();
}

function sayGoodbye() {
    console.log('Goodbye!');
}

greet('Ram', sayGoodbye);
//  Output:
//  Hello Ram !
//  Goodbye!

In this example, sayGoodbye is a callback function passed to the greet function. After greeting, it calls the callback function sayGoodbye.

Promise: A Promise in javascript is an object representing the eventful completion or failure of an asynchronous operation. It is a way to handle asynchronous code in a more organized and readable manner. A Promise can be in one of three states:

  • Pending: The initial state; the promise is neither fulfilled nor rejected.

  • Fulfilled: The operation completed successfully, and the promise has a resulting value.

  • Rejected: The operation failed, and the promise has a reason for the failure.

function asyncTask() {
    return new Promise((resolve, reject) => {
        // Simulating an asynchronous operation
        setTimeout(() => {
            const randomNumber = Math.random();
            if (randomNumber > 0.5) {
                resolve(randomNumber); // Success
            } else {
                reject('Random number is too low'); // Failure
            }
        }, 1000);
    });
}

// Using the Promise
asyncTask()
    .then((result) => {
        console.log('Success:', result);
    })
    .catch((error) => {
        console.error('Error:', error);
    });

async/await: It is a JavaScript feature that allows you to write asynchronous code in a more synchronous-like manner. The async keyword is used to define a function that returns a promise, and the await keyword is used to pause the execution of the function until the promise is resolved or rejected.

async function fetchData() {
    try {
        const result = await aysncTask();
        console.log('Success:', result);
    } catch (error) {
        console.error('Error:', error);
    }
}

fetchData();

Event-driven programming: Event-driven programming is a paradigm where the flow of the program is determined by events such as user actions, sensor outputs, or messages from other programs. The program responds to these events, executing specific code when they occur.

// Define a function to handle button click event
function handleClick() {
    console.log('Button clicked!');
}

// Attach the function to the button's click event
document.getElementById('myButton').addEventListener('click', handleClick);

Summary:

Explored making JavaScript more efficient with callbacks, promises, async/await, and event-driven programming in the blog. These techniques amp up responsiveness and organization in code.