In JavaScript we uses promises for handling async API calls. In JavaScript the Promise takes one argument as a callback containing 2 parameters resolve and reject.
If promise is fulfilled the resolve function will be called and if promise is not fulfilled reject function will be called.
Let me explain with some example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
<script>
var classResult = new Promise((resolve,reject)=>{
let marksObtained = 85;
if(marksObtained >= 80){
resolve('I am the college topper.');
}
else{
reject('I was failed.')
}
});
var gotMedal = new Promise((resolve,reject)=>{
let isTopper = true;
if(isTopper){
resolve('I got the medal.');
}
else{
reject('I got nothing.');
}
});
classResult.then((response)=>{
console.log(response);
})
.catch((error)=>{
console.log(error)
});
gotMedal.then((response)=>{
console.log(response);
})
.catch((error)=>{
console.log(error)
});
</script>
|
Here in this example I have defined 2 promises one is classResult and other is gotMedal. classResult and gotMedal returns promises. If promise resolved then code block executes else catch code block executes. ...