Site icon i2tutorials

Javascript-Promises

Javascript-Promises

 

Promises in real-life express trust between two or more persons and an assurance that a particular thing will surely happen. In javascript, a Promise is an object which ensures to produce of a single value (when required) in the future. The promise in javascript is defined for managing and tackling asynchronous operations.

 

Promise 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 */ }
);

 

Promise Object Properties:

 

 

Promise How To:

 

Here is how to use a Promise:

 

myPromise.then(
 function(value) { /* code if successful */ },
 function(error) { /* code if some error */ }
);

 

Example:

 

<html>
<head>
<h2> Javascript Promise</h2>
</br> </head>
<body>
<script>
var p=new Promise(function(resolve, reject){
var x= 2+3;
if(x==5)
        resolve(" executed and resolved successfully");
else
        reject("rejected");
});
 p.then(function(fromResolve){
 document.write("Promise is"+fromResolve);
 }).catch(function(fromReject){
 document.write("Promise is "+fromReject);
 });
</script>
</body>
</html>

 

 <html>
<head>
<h2> Javascript Promise</h2>
</br> </head>
<body>
<script>
var p=new Promise(function(resolve, reject){
var x= 2+3;
if(x==5)
        resolve(" executed and resolved successfully");
else
        reject("rejected");
});
 p.then(function(fromResolve){
 document.write("Promise is"+fromResolve);
 }).catch(function(fromReject){
 document.write("Promise is "+fromReject);
 });
</script>
</body>
</html>

 

OUTPUT:

 

Promise is executed and resolved successfully

 

 

Exit mobile version