Type something to search...

JavaScript Promises

JavaScript Promises

Promises are used to handle asynchronous operations in JavaScript.

Creating a Promise

A promise represents a value that may be available now, in the future, or never.

let promise = new Promise((resolve, reject) => {
    let success = true;
    if (success) {
        resolve("Operation succeeded!");
    } else {
        reject("Operation failed.");
    }
});

Handling Promises

You can handle the result of a promise using .then() and .catch():

promise
    .then((message) => {
        console.log(message);
    })
    .catch((error) => {
        console.log(error);
    });

Example: Simulating an API Call

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("Data fetched successfully!");
        }, 2000);
    });
}

fetchData()
    .then((data) => {
        console.log(data);
    })
    .catch((error) => {
        console.log("Error:", error);
    });

[End of Tutorial]