andybezbozhny

JavaScript.promises

Nov 11th, 2025
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Creating a Promise */
  2. const myPromise = new Promise((resolve, reject) => {
  3.     let success = true; // Change to false to test rejection
  4.     setTimeout(() => {
  5.         success ? resolve('Promise Resolved!') : reject('Promise Rejected!');
  6.     }, 1000);
  7. });
  8.  
  9. myPromise
  10. .then(result => console.log(result))
  11. .catch(error => console.error(error))
  12. .finally(() => console.log('Promise Completed'));
  13.  
  14. /* Chaining Promises */
  15. const asyncTask = value => new Promise(resolve => setTimeout(() => resolve(value * 2), 1000));
  16.  
  17. asyncTask(5)
  18. .then(result => {
  19.     console.log(result); // 10
  20.     return asyncTask(result);
  21. })
  22. .then(result => console.log(result))
  23. .catch(err => console.log(err));
  24.  
  25. /* Promise.all - Runs all promises in parallel, resolves when all succeed */
  26. Promise.all([asyncTask(2), asyncTask(3), asyncTask(4)])
  27. .then(results => console.log(results)) // [4, 6, 8]
  28. .catch(err => console.error(err));
  29.  
  30. /* Promise.race - Resolves/rejects with the first completed promise */
  31. Promise.race([asyncTask(2), asyncTask(3), asyncTask(4)])
  32. .then(result => console.log(result)) // First resolved value
  33. .catch(err => console.error(err));
  34.  
  35. /* Promise.allSettled - Returns all promise results (fulfilled or rejected) */
  36. Promise.allSettled([asyncTask(2), Promise.reject('Error!'), asyncTask(4)])
  37. .then(results => console.log(results)) // Array of {status, value/reason}
  38.  
  39. /* Promise.any - Resolves with first fulfilled promise (ignores rejections) */
  40. Promise.any([Promise.reject('Error 1'), asyncTask(3), Promise.reject('Error 2')])
  41. .then(result => console.log(result)) // First resolved value
  42. .catch(err => console.error(err.errors)); // Only if all fail
  43.  
  44. // Async/Await Syntax
  45. async function fetchData() {
  46.     try {
  47.         const result = await asyncTask(10);
  48.         console.log(result); // 20
  49.     } catch(err) {
  50.         console.error(err)
  51.     }
  52. }
  53. fetchData();
Advertisement
Add Comment
Please, Sign In to add comment