JS Promise

JS Promise

In JavaScript, a Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. A promise can be in one of three states:

1. Pending: The initial state, where the operation is still in progress.
2. Fulfilled: The operation is completed successfully, and the promise has a resulting value.
3. Rejected: The operation failed, and the promise has a reason for the failure (typically an error).

A Promise allows you to handle asynchronous operations more manageably by attaching handlers for when the operation is either completed or failed, using .then() for success and .catch() for failure.

JS-Promise

Imagine you call a pizza place and order a pizza. The pizza place makes a promise: “We will deliver your pizza soon.” But you don’t know exactly when it will arrive, so you’re in the “Pending” stage. When the pizza arrives, the promise is “Fulfilled” (you get your pizza!). If something goes wrong, like they forget your order or their oven breaks, the promise is “Rejected” (no pizza).

In programming, this process is handled using JavaScript promises, and you can do other tasks while you wait, just like playing games while waiting for your pizza!

Example:

Example:<body>
<script>
let pizzaOrder = new Promise(function(resolve, reject) {
let pizzaReady = true; // Let’s say the pizza is ready

if (pizzaReady) {
resolve(“Your pizza is ready!”);
} else {
reject(“Sorry, there’s a problem with your pizza.”);
}
});
pizzaOrder
.then(function(message) {
console.log(message); // Output: “Your pizza is ready!”
})
.catch(function(error) {
console.log(error); // Output: “Sorry, there’s a problem with your pizza.”
});
</script>
</body>

Creating The Promise:

let pizzaOrder = new Promise(function(resolve, reject) {
let pizzaReady = true; // Let’s say the pizza is ready
if (pizzaReady) {
resolve(“Your pizza is ready!”);
} else {
reject(“Sorry, there’s a problem with your pizza.”);
}
});

Creating a Promise: The new Promise() creates a new promise object. The promise takes a function with two parameters: resolve and reject. These are callback functions used to signal whether the promise is successful or not.

pizzaReady Variable: A boolean variable is used to simulate whether the pizza is ready or not. In this case, it is set to true, indicating the pizza is ready.

resolve(): If the pizzaReady is true, meaning the pizza is ready, the resolve() function is called with the message “Your pizza is ready!”. This signals that the promise has been successfully fulfilled.

reject(): If the pizza isn’t ready (in case pizzaReady was false), the reject() function is called with the message “Sorry, there’s a problem with your pizza.”. This signals that the promise has been rejected, meaning something went wrong.

Handling the Promise Result with .then() and .catch():

pizzaOrder
.then(function(message) {
console.log(message); // Output: “Your pizza is ready!”
})
.catch(function(error) {
console.log(error); // Output: “Sorry, there’s a problem with your pizza.”
});

.then():

  This method is used to handle the fulfilled promise. Once the promise is fulfilled (i.e., when resolve() is called), the function inside .then() is executed.
•  The message parameter holds the value passed to resolve() (“Your pizza is ready!”).
  This function simply logs the message to the console.

.catch():

•  This method is used to handle the rejected promise. If something goes wrong and the promise is rejected (i.e., when reject() is called), the function inside .catch() is executed.
•  The error parameter holds the value passed to reject() (“Sorry, there’s a problem with your pizza.”).
•  This function logs the error message to the console.

Output

Since the pizzaReady variable is set to true in your code, the promise will be fulfilled, and the .then() block will be executed. The output will be:

JS-Handling

If you change pizzaReady to false, the promise will be rejected, and the .catch() block will be executed, producing the output:

JS-Handling-output

Course Video

Practice Scenarios

1. Creating a Basic Promise

Objective: Create a promise that resolves after 2 seconds.

   •  Create a promise that resolves with the string “Resolved!” after a 2-second delay.
   •  Use .then() to handle the resolved value.

Here’s an example program:

const myPromise = new Promise((resolve) => {
setTimeout(() => resolve(“Resolved!”), 2000);
});

myPromise.then((message) => {
console.log(message); // Output after 2 seconds: “Resolved!”
});

Output
JS-Basic-Promise

2. Handling Promise Rejection

Objective: Create a promise that rejects after 1 second.

   •  Create a promise that rejects with the string “Rejected!” after 1 second.
   •  Use .catch() to handle the rejection.

Here’s an example program:

const myPromise = new Promise((_, reject) => {
setTimeout(() => reject(“Rejected!”), 1000);
});

myPromise.catch((message) => {
console.log(message); // Output after 1 second: “Rejected!”
});

Output

3. Using .finally()

Objective: Understand how .finally() works.

   •  Create a promise that either resolves or rejects.
   •  Add a .finally() handler that runs after both resolve and reject, regardless of the outcome.

Here’s an example program:

const myPromise = new Promise((resolve, reject) => {
let success = true;
setTimeout(() => {
if (success) resolve(“Success!”);
else reject(“Failure!”);
}, 1500);
});
myPromise
.then((message) => console.log(message)) // If resolved: “Success!”
.catch((message) => console.log(message)) // If rejected: “Failure!”
.finally(() => console.log(“Always runs.”)); // Always: “Always runs.”

Output
JS-Usinga

4. Chaining Multiple .then() Calls

Objective: Chain multiple .then() calls to process data step-by-step.

   • Create a promise that resolves with a number.
   • Use multiple .then() calls to perform arithmetic operations in sequence.

Here’s an example program:

const myPromise = new Promise((resolve) => {
resolve(5);
});

myPromise
.then((value) => value + 3) // 5 + 3 = 8
.then((value) => value * 2) // 8 * 2 = 16
.then((value) => value – 4) // 16 – 4 = 12
.then((value) => console.log(value)); // Output: 12

Output
JS-Chaining-mAultiple

5. Promise.all()

Objective: Use Promise.all() to handle multiple promises concurrently.

   •  Create three promises that resolve after different time intervals.
   •  Use Promise.all() to handle all promises together and print the results when all are resolved.

Here’s an example program:

const promise1 = new Promise((resolve) => setTimeout(() => resolve(“First”), 1000));
const promise2 = new Promise((resolve) => setTimeout(() => resolve(“Second”), 2000));
const promise3 = new Promise((resolve) => setTimeout(() => resolve(“Third”), 3000));

Promise.all([promise1, promise2, promise3])
.then((values) => console.log(values)); // Output: [“First”, “Second”, “Third”]

Output

6. Promise.race()

Objective: Use Promise.race() to handle the first promise that resolves or rejects.

   •  Create three promises that resolve or reject at different times.
   •  Use Promise.race() to handle the result of the first promise to settle (either resolve or reject).

Here’s an example program:

const promise1 = new Promise((resolve) => setTimeout(() => resolve(“First”), 3000));
const promise2 = new Promise((resolve) => setTimeout(() => resolve(“Second”), 1000));
const promise3 = new Promise((resolve) => setTimeout(() => resolve(“Third”), 2000));

Promise.race([promise1, promise2, promise3])
.then((value) => console.log(value)); // Output: “Second”

Output
JS-Promise-race

7. Promise.allSettled()

Objective: Use Promise.allSettled() to handle multiple promises, whether they resolve or reject.

   •  Create two promises: one that resolves and one that rejects.
   •  Use Promise.allSettled() to handle both promises and print the results, even if some fail.

Here’s an example program:

const promise1 = new Promise((resolve) => resolve(“Resolved”));
const promise2 = new Promise((_, reject) => reject(“Rejected”));

Promise.allSettled([promise1, promise2])
.then((results) => console.log(results)); // Output:
// [
// { status: “fulfilled”, value: “Resolved” },
// { status: “rejected”, reason: “Rejected” }
// ]

Output

8. Async/Await Syntax

Objective: Use async and await to handle promises in a cleaner way.

   •  Create an async function that uses await to handle a promise.
   •  Return a value from the async function that resolves with “Completed”.

Here’s an example program:

const myPromise = new Promise((resolve) => {
setTimeout(() => resolve(“Completed”), 2000);
});

async function myAsyncFunction() {
const result = await myPromise;
console.log(result); // Output after 2 seconds: “Completed”
}

myAsyncFunction();

Output
JS-Async

9. Handling Multiple Promises with Promise.all() and .catch()

Objective: Use Promise.all() with error handling.

   •  Create three promises: two resolve successfully, and one rejects.
   •  Use .catch() to handle the rejection in case any promise fails

Here’s an example program:

const promise1 = new Promise((resolve) => resolve(“Success 1”));
const promise2 = new Promise((resolve) => resolve(“Success 2”));
const promise3 = new Promise((_, reject) => reject(“Failure”));
Promise.all([promise1, promise2, promise3])
.then((results) => console.log(results))
.catch((error) => console.log(error)); // Output: “Failure”

Output
JS-Handling-multiple

10. Chaining Promises with Errors

Objective: Handle errors in promise chains.

   •  Create a promise that resolves successfully.
   •  Add a .then() that intentionally throws an error.
   •  Use .catch() to handle the error in the chain.

Here’s an example program:

const myPromise = new Promise((resolve) => resolve(“Initial success”));

myPromise
.then((message) => {
console.log(message); // “Initial success”
throw new Error(“Something went wrong!”);
})
.catch((error) => {
console.log(error.message); // “Something went wrong!”
});

Output
JS-Chaining
Frequently Asked Questions

Still have a question?

Let's talk

A Promise represents the eventual completion or failure of an asynchronous operation, and its resulting value. Learn more in our JavaScript promise free course video.

A Promise has three states:

  • Pending: Initial state, neither fulfilled nor rejected.
  • Fulfilled: The operation was successful.
  • Rejected: The operation failed.
    Discover these states in the JS promise with free video tutorial.

Use the new Promise() constructor.
Example:

let promise = new Promise((resolve, reject) => { 

  let success = true; 

  if (success) resolve(“Done!”); 

  else reject(“Error!”); 

}); 

Learn how to implement this in the Free JavaScript promise tutorial for beginners.

  • then(): Handles the resolved value.
  • catch(): Handles errors (rejections).
    Example:

promise 

  .then(result => console.log(result)) 

  .catch(error => console.log(error)); 

Explore their uses in the JavaScript promise with free tutorial.

Yes, you can chain then() to process data sequentially.
Example:

promise 

  .then(result => result + ” processed”) 

  .then(final => console.log(final)); 

Learn more in the JavaScript promise free course video.

Promise.all() executes multiple Promises concurrently and resolves when all Promises resolve, or rejects if any Promise fails. Watch examples in the JS promise with free video tutorial.

Promise.race() resolves or rejects as soon as any of the Promises in the iterable resolve or reject. Check this out in the Free JavaScript promise tutorial for beginners.

Promises provide better error handling and chaining, avoiding callback hell, which occurs with deeply nested callbacks. Find this explained in the JavaScript promise with free tutorial.

  1. Use new Promise() to wrap the callback.
    Example:

function asyncTask(callback) { 

  return new Promise((resolve, reject) => { 

    callback(error, result => { 

      if (error) reject(error); 

      else resolve(result); 

    }); 

  }); 

Discover more in the JavaScript promise free course video.

  • Always return Promises for chaining.
  • Use catch() for error handling.
  • Prefer async/await for better readability.
    Learn these best practices in the JS promise with free video tutorial.