Promises and Fetch API

Promises:

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It provides a way to handle asynchronous code more elegantly.

                                      
                                        // Example: Simulating an asynchronous operation
const fetchData = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const success = Math.random() > 0.5;
            if (success) {
                resolve('Data fetched successfully');
            } else {
                reject(new Error('Failed to fetch data'));
            }
        }, 1000);
    });
};

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

In this example, fetchData returns a Promise. The then method is used to handle the resolved value, and the catch method is used to handle errors.


Fetch API:

The Fetch API provides a modern, promise-based way to make network requests. It is widely used for making HTTP requests and handling responses.

                                      
                                        // Example: Making a GET request with fetch
fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        console.log('Data:', data);
    })
    .catch(error => {
        console.error('Error:', error.message);
    });
                                      
                                    

In this example, fetch returns a Promise that resolves to the Response to that request, whether it is successful or not. The json method is used to extract JSON data from the response.


Async/Await:

Async/await is a syntax for handling asynchronous code that makes it look and behave like synchronous code. It's built on top of promises.

                                      
                                        // Using async/await with fetch
async function fetchData() {
    try {
        const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        const data = await response.json();
        console.log('Data:', data);
    } catch (error) {
        console.error('Error:', error.message);
    }
}

fetchData();                                            
                                      
                                    

In this example, fetchData is an asynchronous function that uses await to wait for the promises returned by fetch and response.json() to resolve.


Hey there! Let's go for Learn fasta then! It is more than just coding; it is to have the superpower that can solve any problem. Through simple and easy-to-grasp examples you will sail through the learning process. In addition, it is not just about coding– you will acquire competencies on how to solve complex problems, analyze data, and come up with efficient solutions. Shall we start this wonderful journey together! learnfasta.com terms of use, Copyright 2025 All Rights Reserved.