JavaScript Promises

A JavaScript Promise is an object representing the eventual completion or failure of an asynchronous operation. It allows you to handle asynchronous operations more elegantly and provides a way to perform tasks asynchronously and handle their results later.

Here's a real-life example story to illustrate JavaScript Promise:

Imagine you're a student waiting for your exam results. You have no control over when the results will be available, but you want to be prepared to celebrate or console yourself based on the outcome. So, you decide to use a Promise to represent this situation.

  • In this example, waitForExamResults is a Promise representing the process of waiting for exam results. Inside the Promise constructor function, there's a simulation of obtaining the exam score asynchronously after a delay of 3 seconds.

  • If the exam score is 60 or higher, the Promise resolves with a success message indicating the passing score. Otherwise, it rejects with an error message indicating failure.

  • The then() method is used to handle the fulfillment of the Promise (passing scenario), and the catch() method is used to handle the rejection of the Promise (failing scenario).

  • When you run this code, it first logs "Waiting for exam results...". After 3 seconds, it logs either "Success: Congratulations! You passed the exam with a score of X." or "Error: Sorry, you failed the exam with a score of X.", depending on the randomly generated exam score.