In JavaScript, a Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It provides a cleaner and more efficient way to handle asynchronous code compared to traditional callback-based approaches.
A Promise has three states:
Promises can be used to handle various asynchronous operations such as fetching data from APIs, making HTTP requests, reading/writing files, and more. Promises can be chained together using the .then() method, allowing for sequential execution of asynchronous operations. Additionally, Promises can be combined using methods like Promise.all() and Promise.race() to handle multiple asynchronous operations concurrently.
ES6 introduced the async/await syntax, which is built on top of Promises and provides a more concise way to write asynchronous code. async functions return Promises, and await is used to pause the execution of an asynchronous function until the Promise is fulfilled or rejected.
Key features of Promises in JavaScript:
Overall, Promises in JavaScript provide a powerful tool for managing asynchronous code, making it more manageable, readable, and error-resistant.
then() is a method available on Promise objects. It is used to attach callbacks or handlers that will be executed when a Promise is fulfilled, i.e., when the asynchronous operation associated with the Promise completes successfully.
The syntax for using then() is as follows:
promise.then(onFulfilled, onRejected);
where promise is the Promise object, onFulfilled is a callback function that will be executed when the Promise is fulfilled, and onRejected is an optional callback function that will be executed when the Promise is rejected
The onFulfilled callback function will receive the resolved value of the Promise as its first argument. If the Promise does not have a resolved value, onFulfilled will receive undefined. The onRejected callback function, if provided, will receive the reason or error associated with the rejected Promise as its first argument.
The resolve and reject functions are provided as arguments to the Promise constructor, and they are used to fulfill or reject the Promise, respectively, when the asynchronous operation completes.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="icon" type="image/ico" href="logo.png" /> <title>Document</title> <style> @import url("https://fonts.googleapis.com/css2?family=Lobster&family=Poppins:wght@100;200;300;400;500;600;700;800&display=swap"); * { font-family: "Poppins", sans-serif; } </style> </head> <body> <h3>Promise in JavaScript</h3> <button>Click Me</button> <script src="117_promise.js"></script> </body> </html>
/* const promise = new Promise((resolve, reject) => { const sum = 22 + 1; if (sum == 2) { resolve("Success"); } else { reject("Error"); } }); promise .then((msg) => { console.log(msg); }) .catch((error) => { console.error(error); }); */ /* setTimeout(() => { console.log("Hi"); }, 250); function setTimeoutPromise(duration) { return new Promise((resolve, reject) => { setTimeout(resolve, duration); }); } setTimeoutPromise(250).then(() => { console.log("Joes"); }); */ /* setTimeout(() => { console.log("Normal : 1"); setTimeout(() => { console.log("Normal : 2"); setTimeout(() => { console.log("Normal : 3"); }, 250); }, 250); }, 250); function setTimeoutPromise(duration) { return new Promise((resolve, reject) => { setTimeout(resolve, duration); }); } setTimeoutPromise(250).then(() => { console.log("Normal SetTime : 1"); setTimeoutPromise(250).then(() => { console.log("Normal SetTime : 2"); setTimeoutPromise(250).then(() => { console.log("Normal SetTime : 3"); }); }); }); setTimeoutPromise(250) .then(() => { console.log("Cool Promise : 1"); return setTimeoutPromise(250); }) .then(() => { console.log("Cool Promise : 2"); return setTimeoutPromise(250); }) .then(() => { console.log("Cool Promise : 3"); }); */ /* const button = document.querySelector("button"); function addEventPromise(element, method) { return new Promise((resolve, reject) => { element.addEventListener(method, resolve); }); } addEventPromise(button, "click").then((e) => { console.log("Clicked"); console.log(e); }); */ /* console.log(Promise.resolve("Good")); Promise.all([Promise.resolve("Good"), Promise.resolve("Good"), Promise.resolve("Good")]) .then((msg) => { console.log(msg); }) .catch((error) => { console.error(error); }); Promise.all([Promise.resolve("Good"), Promise.reject("Error"), Promise.resolve("Good")]) .then((msg) => { console.log(msg); }) .catch((error) => { console.error(error); }); Promise.any([Promise.reject("1"), Promise.reject("Error"), Promise.resolve("3")]) .then((msg) => { console.log(msg); }) .catch((error) => { console.error(error); }); Promise.race([Promise.reject("Good-1"), Promise.resolve("Good-2"), Promise.resolve("Good-3")]) .then((msg) => { console.log(msg); }) .catch((error) => { console.error(error); }); Promise.allSettled([Promise.reject("Good-1"), Promise.resolve("Good-2"), Promise.resolve("Good-3")]) .then((msg) => { console.log(msg); }) .catch((error) => { console.error(error); }); */ /* const promise = Promise.reject("Error"); promise .then((msg) => { console.log(msg); }) .catch((err) => { console.error(err); }) .finally(() => { console.log("All Completed.."); }); */ /* const getPost = () => { return new Promise((resolve, reject) => { setTimeout(() => { const posts = ["Post-1", "Post-2", "Post-3"]; resolve(posts); }, 1000); }); }; const getComments = () => { return new Promise((resolve, reject) => { setTimeout(() => { const comments = ["Comment 1", "Comment 2", "Comment 3"]; resolve(comments); }, 2000); }); }; Promise.all([getPost(), getComments()]) .then((results) => { //console.log(results); const [posts, comments] = results; console.log(`Posts: ${posts}`); console.log(`Comments: ${comments}`); }) .catch((err) => { console.error(err); }); */ /* fetch("https://jsonplaceholder.typicode.com/users") .then((response) => response.json()) .then((data) => { console.log(data); }) .catch((err) => { console.error(err); }); */
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions