w1coding.comAll tutorials

JavaScript Promises

JavaScript lessons
  1. Environment Setup
  2. Introduction
  3. Enviroment
  4. Basics
  5. Variables
  6. Operators
  7. Condition
  8. Functions
  9. Arrays
  10. Bjects
  11. DOM
  12. Objects
  13. Colors
  14. DOM
  15. Events
  16. Validation
  17. JSON
  18. Error
  19. Callbacks
  20. Promises
  21. Fetch
  22. Local
  23. Modules
  24. Animation
  25. Classes
  26. Iframes
  27. Responsive

Promises in JavaScript

Promises are a cleaner way to handle asynchronous operations in JavaScript.

Creating a Promise

A promise represents the completion (or failure) of an asynchronous operation and its resulting value:

      
        let myPromise = new Promise(function(resolve, reject) {
          let success = true;
          if (success) {
            resolve("Operation successful");
          } else {
            reject("Operation failed");
          }
        });

        myPromise
          .then(function(value) {
            console.log(value); // Outputs: Operation successful
          })
          .catch(function(error) {
            console.log(error);
          });
      
    

Activity

Try It Yourself!

Create a promise that simulates an operation, resolves if successful, or rejects with an error message.

Quiz

Quick Quiz

  1. What is a promise in JavaScript?
  2. What is the purpose of the then method?
  3. How do you handle errors in promises?

Answers: An object representing the completion or failure of an async operation; handles successful results; use catch to handle errors.