Promises

Promises were introduced to address the callback hell issue and provide a more structured way of handling asynchronous code. A Promise is an object representing the eventual completion or failure of an asynchronous operation.

Promises provide a more structured way to handle asynchronous code and simplify error handling. They can be chained using .then() and .catch().

Example: Here, fetchUserDataWithPromise returns a Promise, simulating the asynchronous nature of an API request. The .then() method handles the resolved value, and the .catch() method handles errors.

Javascript




// Function to fetch user data with a Promise
function fetchUserDataWithPromise() {
    // Simulating an API request
    const userData = { id: 1, name: "John Doe" };
 
    return new Promise((resolve, reject) => {
        if (userData) {
            resolve(userData);
        } else {
            reject("Error fetching user data.");
        }
    });
}
 
// Using the Promise
fetchUserDataWithPromise()
    .then((data) => {
        console.log("Processing user data:", data);
        console.log("User data processed successfully.");
    })
    .catch((error) => {
        console.error("Error:", error);
    });


Output

Processing user data: { id: 1, name: 'John Doe' }
User data processed successfully.

Callbacks vs Promises vs Async/Await

Callbacks, Promises, and Async/Await are three different approaches in JavaScript for handling asynchronous operations. Let’s briefly discuss each.

Similar Reads

Callback

Callbacks are functions passed as arguments to other functions, and they are executed after the completion of a specific task. Callbacks have been a traditional way of handling asynchronous operations in JavaScript....

Promises

...

Async/Await

Promises were introduced to address the callback hell issue and provide a more structured way of handling asynchronous code. A Promise is an object representing the eventual completion or failure of an asynchronous operation....

Contact Us