Promises are a method by which we can handle Asynchronous Requests in a better way. Normally a Promise has three output conditions:
a. RESOLVED
b. PENDING
c. REJECT
Just imagine a Promise that your father made, for buying a good phone. It would have three conditions:
a. RESOLVED - Your father got you a new phone.
b. REJECTED - You didn't get a new phone.
c. PENDING - The promise is neither rejected or fulfilled, still you are waiting for the phone
The following code shows how we can handle the Promises.
The value of Result is:200
The output is 200 as the condition was true and we returned Promise.resolve(x). In case the condition was false, it would have returned Promise.reject.
Also, remember .then is the function that is represented for Promise.resolve.
a. RESOLVED
b. PENDING
c. REJECT
Just imagine a Promise that your father made, for buying a good phone. It would have three conditions:
a. RESOLVED - Your father got you a new phone.
b. REJECTED - You didn't get a new phone.
c. PENDING - The promise is neither rejected or fulfilled, still you are waiting for the phone
The following code shows how we can handle the Promises.
function checkValue(x){
if(x > 100){
return Promise.resolve(x);
}
else{
return Promise.reject(new Error("the value is less than 100!"));
}
}
var result = checkValue(200);
result.then((value)=>{
console.log("The value of Result is:"+value);
})
.catch(function(err){
console.log("The error is :"+err);
})
The above code will generate the following:The value of Result is:200
The output is 200 as the condition was true and we returned Promise.resolve(x). In case the condition was false, it would have returned Promise.reject.
Also, remember .then is the function that is represented for Promise.resolve.
Comments