Promises... in JavaScript

JavaScript promises are a way to handle asynchronous operations in a cleaner and more readable way compared to traditional callback-based approaches. They represent a value that might be available now, or in the future, or never.

States of a Promise

  1. Pending: The initial state. The operation has not yet completed.
  2. Fulfilled: The operation has completed successfully, and the promise has a resulting value.
  3. Rejected: The operation has failed, and the promise has a reason (an error).

Creating a Promise

A promise is created using the Promise constructor, which takes a function (executor) with two arguments:

  • resolve: A function to mark the promise as fulfilled.
  • reject: A function to mark the promise as rejected.

    <script>

       var complete = true;

       var abc = new Promise(function(resolve,reject){
        if(complete){
            resolve("Yes!...")
        }else{
            reject("No! its failed")
        }
       });

       console.log(abc);

    </script>