promises
Fri Jun 14 2024 09:20:41 GMT+0000 (Coordinated Universal Time)
Saved by @devdutt
Promises are a fundamental concept in JavaScript for managing asynchronous operations. They represent a value that may be available now, or in the future, or never. Understanding promises is crucial for handling asynchronous code more effectively and avoiding callback hell. Key Concepts of Promises State: A promise can be in one of three states: Pending: The initial state, neither fulfilled nor rejected. Fulfilled: The operation completed successfully. Rejected: The operation failed. Value: Once a promise is fulfilled, it has a value. If it’s rejected, it has a reason (an error). Settled: A promise is settled if it is either fulfilled or rejected. Creating Promises You can create a promise using the Promise constructor, which takes a function (executor) with two arguments: resolve and reject. javascript Copy code const myPromise = new Promise((resolve, reject) => { const success = true; // Simulate an async operation if (success) { resolve('Operation was successful!'); } else { reject('Operation failed.'); } }); Handling Promises then Method Used to handle a fulfilled promise and to chain multiple promises. javascript Copy code myPromise.then(value => { console.log(value); // "Operation was successful!" }).catch(error => { console.error(error); // "Operation failed." }); catch Method Used to handle a rejected promise. javascript Copy code myPromise.catch(error => { console.error(error); // "Operation failed." }); finally Method Runs regardless of the promise’s outcome. javascript Copy code myPromise.finally(() => { console.log('Promise has been settled.'); }); Chaining Promises You can chain multiple then calls to handle a sequence of asynchronous operations. javascript Copy code myPromise .then(value => { console.log(value); return 'Next operation'; }) .then(nextValue => { console.log(nextValue); }) .catch(error => { console.error(error); }) .finally(() => { console.log('All done!'); }); Promise Methods Promise.all Waits for all promises to settle and returns an array of their results. If any promise rejects, it immediately rejects with that reason. javascript Copy code const promise1 = Promise.resolve('First'); const promise2 = Promise.resolve('Second'); const promise3 = Promise.resolve('Third'); Promise.all([promise1, promise2, promise3]) .then(values => { console.log(values); // ["First", "Second", "Third"] }) .catch(error => { console.error(error); }); Promise.race Returns the first promise that settles (either fulfills or rejects). javascript Copy code const promise1 = new Promise((resolve) => setTimeout(resolve, 500, 'First')); const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'Second')); Promise.race([promise1, promise2]) .then(value => { console.log(value); // "Second" }) .catch(error => { console.error(error); }); Promise.allSettled Waits for all promises to settle and returns an array of their results with their status. javascript Copy code const promise1 = Promise.resolve('First'); const promise2 = Promise.reject('Error'); const promise3 = Promise.resolve('Third'); Promise.allSettled([promise1, promise2, promise3]) .then(results => { results.forEach((result) => console.log(result.status)); // "fulfilled" // "rejected" // "fulfilled" }); Promise.any Returns the first promise that fulfills, ignoring rejections. javascript Copy code const promise1 = Promise.reject('Error 1'); const promise2 = Promise.reject('Error 2'); const promise3 = Promise.resolve('First successful'); Promise.any([promise1, promise2, promise3]) .then(value => { console.log(value); // "First successful" }) .catch(error => { console.error('All promises were rejected', error); }); Using Async/Await async and await provide a more readable way to work with promises, allowing you to write asynchronous code that looks synchronous. javascript Copy code async function fetchData() { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error fetching data:', error); } finally { console.log('Fetch operation complete.'); } } fetchData(); Summary Promises simplify asynchronous programming by providing a clear and manageable way to handle asynchronous operations. then, catch, and finally methods help in handling fulfilled, rejected, and settled promises. Promise methods like all, race, allSettled, and any provide utilities for managing multiple promises. Async/await syntax allows for writing asynchronous code in a synchronous style, improving readability.
Comments