Wednesday, July 3, 2024
HomeLanguagesJavascriptAsynchronous JavaScript

Asynchronous JavaScript

Asynchronous JavaScript is a programming approach that enables the non-blocking execution of tasks, allowing concurrent operations, improved responsiveness, and efficient handling of time-consuming operations in web applications, JavaScript is a single-threaded and synchronous language. The code is executed in order one at a time, But Javascript may appear to be asynchronous in some situations.

There are several methods that can be used to perform asynchronous javascript tasks, which are listed below:

Approach 1: Using callback

Callbacks are functions passed as arguments to be executed after an asynchronous operation completes. They are used in asynchronous JavaScript to handle responses and ensure non-blocking execution,

Syntax:

function myFunction(param1, param2, callback) {
// Do some work...
// Call the callback function
callback(result);
}

Example: In this example, the myFunction simulates an async task with a 3s delay. It passes fetched data to the callback, which logs it. Output after 3s:

Javascript




function myFunction(callback) {
    setTimeout(() => {
        const data = { name: "Aman", age: 21 };
        callback(data);
    }, 3000);
}
  
myFunction((data) => {
    console.log("Data:", data);
});


Output:

Data: { name: 'Aman', age: 21 }

Approach 2: Using Promises

Promises are objects representing the eventual completion (or failure) of an asynchronous operation, providing better handling of asynchronous code with .then() and .catch().

Syntax:

let promise = new Promise(function(resolve, reject){
//do something
});

Example: In this example, The function mydata() returns a Promise that resolves with data after a delay. The data is logged, or an error is caught if rejected, after 2 seconds.

Javascript




function mydata() {
  
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const data = { name: "Rohit", age: 23 };
            resolve(data);
        }, 2000);
    });
}
  
mydata()
    .then((data) => {
        console.log("Data:", data);
    })
    .catch((error) => {
        console.error("Error:", error);
    });


Output:

Data: { name: 'Rohit', age: 23 }

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments