-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path10-Async-await.js
More file actions
78 lines (69 loc) · 2.2 KB
/
10-Async-await.js
File metadata and controls
78 lines (69 loc) · 2.2 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Async functions always return a Promise. If the function throws an error,
// the Promise will be rejected. If the function returns a value, the Promise will be resolved.
let getData=function(message){
return new Promise(function(resolve,reject){
resolve("abhinav is saying "+message+"! You want more?");
});
}
let getMoreData=function(message){
return new Promise(function(resolve,reject){
resolve("Rahul is saying "+message+"! You want more??");
});
}
let getSomeMoreData=function(message){
return new Promise(function(resolve,reject){
resolve("Gagan is saying "+message+"! You want more??");
});
}
let get_SomeMore=function(message){
return new Promise(function(resolve,reject){
resolve("Nirmal is saying "+message+"! GOODBYE!!!");
});
}
async function data(){
try{
const fromResolve1 = await getData("Hi!");
console.log(fromResolve1);
const fromResolve2 = await getData("Hello!");
console.log(fromResolve2);
const fromResolve3 = await getData("Kidaan!");
console.log(fromResolve3);
const fromResolve4 = await getData("Chad di kala");
console.log(fromResolve4);
}
catch(err){
console.log(err);
}
}
data();
//One more example----------------------------------------------------------------------------------------------------
function makeRequest(location){
return new Promise(function(resolve,reject){
console.log("making request to "+location);
if(location==='google'){
resolve('Google says Hi!');
}
else{
reject('We can only talk to google');
}
});
}
function processRequest(response){
return new Promise(function(resolve,reject){
console.log("Processing response");
resolve("Extra info "+response);
});
}
async function doWork(){
try{
const response=await makeRequest('google');
console.log("Response received");
const processedResponse=await processRequest(response);
console.log(processedResponse);
}
catch (err)
{
console.log(err);
};
}
doWork();