-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path37 promises vs callback example.html
84 lines (76 loc) · 2.59 KB
/
37 promises vs callback example.html
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
79
80
81
82
83
84
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const userLeft = false
const userIsWatchingMeme = false
console.log("using callback")
//using callbacks
//this function takes two variables one for success and one for error
function checkUserActivity(callback, errorCallback) {
if (userLeft) {
errorCallback({
name: "user has left",
message: " ok bye"
})
} else if (userIsWatchingMeme) {
errorCallback({
name: "user is watching memes",
message: "and he is enjoying!"
})
} else {
callback('user is still coding...')
// console.log("callback function:",callback) // see its o/p its function passed to it
}
}
checkUserActivity((message) => {
console.log('success: ', message)
}, (error) => {
console.log(error.name + " " + error.message)
})
console.log("now using promises")
const userLeft1 = false
const userWatchingMeme1 = false
//now lets do it using promises
function usingPromises() {
return new Promise((resolve, reject) => {
if (userLeft1) {
reject({
name: "user has left",
message: "ok bye"
})
} else if (userWatchingMeme1) {
reject({
name: "user is watching memes",
message: "so sad"
})
} else {
resolve('thanku for coding it')
}
})
}
usingPromises().then((message)=>{
console.log('success: '+message)
}).catch((errors)=>{
console.log(errors.name+' '+errors.message)
})
//its better two use promises then nested callbacks and in prmoises instead of nesting callbacks
//use another then like this:
/*
usingPromises().then((message)=>{
console.log('success: '+message)
}).then((message)=>{
console.log('success: '+message)
}).catch((errors)=>{
console.log(errors.name+' '+errors.message)
})
*/
</script>
</body>
</html>