-
Notifications
You must be signed in to change notification settings - Fork 839
/
Promise-simple-Example.js
81 lines (68 loc) · 1.69 KB
/
Promise-simple-Example.js
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
const isMomHappy = true;
// Define a function to return a Promise
const willIGetNewPhone = new Promise((resolve, reject) => {
if (isMomHappy) {
const phone = {
brand: "Samsung",
color: "black"
};
resolve(phone);
} else {
const reason = new Error("Mom is not happy");
reject(reason);
}
});
const showOff = phone => {
const message =
"Hey friend, I have a new " + phone.color + " " + phone.brand + " phone";
return Promise.resolve(message);
};
// call out promise
const askMom = () => {
willIGetNewPhone
.then(showOff)
.then(fullfilled => console.log(fullfilled))
.then(error => console.log(error.message));
};
askMom();
// Same above example with ES-8 async-await
//
// const isMomHappy = true;
// Promise
const willIGetNewPhone = new Promise((resolve, reject) => {
if (isMomHappy) {
const phone = {
brand: "Samsung",
color: "black"
};
resolve(phone);
} else {
const reason = new Error("mom is not happy");
reject(reason);
}
});
// 2nd promise
async function showOff(phone) {
return new Promise((resolve, reject) => {
var message =
"Hey friend, I have a new " + phone.color + " " + phone.brand + " phone";
resolve(message);
});
}
// call our promise
async function askMom() {
try {
console.log("before asking Mom");
let phone = await willIGetNewPhone;
let message = await showOff(phone);
console.log(message);
console.log("after asking mom");
} catch (error) {
console.log(error.message);
}
}
(async () => {
await askMom();
})();
/*Further Reading -
[https://scotch.io/tutorials/javascript-promises-for-dummies](https://scotch.io/tutorials/javascript-promises-for-dummies)*/