JavaScript Promises

Overview

JavaScript Promises provide a way to work with asynchronous operations in a more structured and manageable way. Promises represent a future value that may not be available immediately, such as data fetched from a server, and allow you to handle success and error cases gracefully.


Creating Promises

You can create a new Promise using the Promise constructor, which takes a function with two arguments: resolve and reject. Inside this function, you perform an asynchronous operation and call resolve when it's successful or reject when it fails.

Try yourself
        
            
function fetchData(url) {
    return new Promise(function(resolve, reject) {
        // Simulate an asynchronous operation
        setTimeout(function() {
            let data = 'Fetched data from ' + url;
            if (data) {
                resolve(data); // Resolve the Promise with data
            } else {
                reject('Failed to fetch data'); // Reject the Promise with an error
            }
        }, 2000); // Simulate a 2-second delay
    });
}

let promise = fetchData('https://example.com/api');

        
    

Promise States

A Promise can be in one of three states:


Consuming Promises

To consume a Promise, you can use the .then() method to specify what to do when the Promise is fulfilled. You can also use the .catch() method to handle errors.

Try yourself
        
            
let promise = fetchData('https://example.com/api');

promise
    .then(function(data) {
        console.log('Data:', data);
    })
    .catch(function(error) {
        console.error('Error:', error);
    });

        
    

Chaining Promises

Promises can be chained together to perform a series of asynchronous operations sequentially. This is achieved by returning a new Promise from within the .then() method.

Try yourself
        
            
function fetchUserDetails(userId) {
    return fetchData('https://example.com/api/users/' + userId);
}

function fetchPosts(userId) {
    return fetchData('https://example.com/api/posts/' + userId);
}

fetchUserDetails(123)
    .then(function(userData) {
        console.log('User Data:', userData);
        return fetchPosts(userData.id);
    })
    .then(function(postData) {
        console.log('Posts:', postData);
    })
    .catch(function(error) {
        console.error('Error:', error);
    });

        
    

Error Handling

Error handling in Promises is done using the .catch() method or by chaining .then() with two functions: one for success and one for failure.

Try yourself
        
            
fetchData('https://example.com/api')
    .then(function(data) {
        console.log('Data:', data);
    })
    .catch(function(error) {
        console.error('Error:', error);
    });

        
    

Promises vs. Callbacks

Promises offer a more structured and readable way to handle asynchronous operations compared to traditional callbacks. They also provide better error handling and make it easier to work with multiple asynchronous tasks.


Summary

JavaScript Promises are a powerful tool for managing asynchronous operations. They simplify handling of asynchronous tasks, provide better error management, and support chaining for sequential operations. Understanding and using Promises effectively is essential for writing robust and responsive JavaScript code.