Course Banner


JavaScript Promise Object

Wait 3 seconds (5000 milliseconds) for this page to change.

<h1 id="result"></h1>

<script>

let objPromise = new Promise(function(Resolve, Reject) {

  setTimeout(function(){ Resolve("Operation Successful!"); }, 3000);

});

objPromise.then(function(value) {

  document.getElementById("result").innerHTML = value;

});

</script>

Promise acts as a chain between producing code and consuming code.
There is a direct relation between the code where the production code is executed and the code where the produced code is consumed.

 

Sometimes, it takes time to produce the code.By that time the consuming code has to wait.

 

Why use Promises?

a.It enhances Code Readability

b.Enhanced handling of asynchronous operations

c. Enhanced flow of control definition in asynchronous logic

Better Error Handling

A Promise has four states:

rejected: If the code fail to execute properly

fulfilled: If the code executes perfectly

pending: When no rejected or no accepted 

settled: Ether Promise has been fulfilled or rejected

JavaScript Promise Example

let  objPromise = new Promise(function(Resolve, Reject) {

// "Producing Code" (May take some time)

  Resolve(); // when successful

  Reject();  // when error

});

// "Consuming Code" (Must wait for a fulfilled Promise).

objPromise.then(

  function(value) { /* code if successful */ },

  function(error) { /* code if some error */ }

);

Below is the practical Example of Promises in Javascript

<!DOCTYPE html>

<html>

<body>

<h2>Example of Promise</h2>

</body>

</html>

Another example :

<!DOCTYPE html>

<html>

<body>

<h2>Example of Promise</h2>

 

<p>Wait 3 seconds (5000 milliseconds) for this page to change.</p>

<h1 id="result"></h1>

<script>

let objPromise = new Promise(function(Resolve, Reject) {

  const x = "acesoftech"; 

  const y = "acesoftech"

  if(x === y) { 

    Resolve(); 

  } else { 

    Reject(); 

  } 

});

  objPromise.then(function () { 

       document.getElementById("result").innerHTML = 'acesoftech';

    }). 

    catch(function () { 

        document.getElementById("result").innerHTML = 'Different';

  }); 

</script>

</body>

</html>