Introduction
Promises are a really interesting feature in Jquery used to manage asynchronous events. They always allow for clear callback logic. Here, we are going to see what are promises, how to define the concept, how to use it, and how to execute a promise in an asynchronous way.
Basic Idea
Promises in Javascript are like making a promise in real life. If a bike mechanic gives a promise to service your bike by end of the day, either by end of the day he finishes his promise by servicing your bike or he fails. In Javascript, promises are similar.
By learning the basic idea of promise, you can easily manage asynchronous concepts in Javascript.
What are Promises?
Define a Promise
- let promiseBikeService = new Promise(function(resolve, reject){
-
- });
The keyword "new Promise" acts as a callback function. The callback function takes two arguments, one is "resolve" and another is "reject".
How to Use the Promise
- let promiseBikeService = new Promise(function(resolve, reject){
-
- let doService = true;
-
- if(doService){
- resolve('serviced');
- }
- else {
- reject('not serviced');
- }
- });
How to execute a Promise
- promiseBikeService.then(function(fromResolve){
- console.log('The bike is' + fromResolve);
- }).catch(function(fromReject){
- console.log('The bike is' + fromReject);
- });
The keyword "then" function will be triggered when the deffered is resolved.
The keyword "catch" function will be triggered when the deffered is rejected.
Summary
This is the basic idea of javascript promise. We have learned what is a promise, how to define a promise, and how to execute a promise. Please add your valuable comments.
<Always be coding>