romises

Promises in JavaScript

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.