Difference Between JavaScript Promise and JavaScript Observable



JavaScript Promise:

Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.


A JavaScript Promise object can be:

  • Pending

  • Fulfilled

  • Rejected


The Promise object supports two properties: state and result. While a Promise object is "pending" (working), the result is undefined. When a Promise object is "fulfilled", the result is a value. When a Promise object is "rejected", the result is an error object.


Syntax:

let myPromise = new Promise(function(myResolve, myReject) 
{

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

  myResolve(); // when successful
  myReject();  // when error
});

// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);

Code:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Promi