Skip to content

Commit 936f3dc

Browse files
committed
Promise example
1 parent ebdbb8f commit 936f3dc

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
const isMomHappy = true;
2+
3+
// Define a function to return a Promise
4+
const willIGetNewPhone = new Promise((resolve, reject) => {
5+
if (isMomHappy) {
6+
const phone = {
7+
brand: "Samsung",
8+
color: "black"
9+
};
10+
resolve(phone);
11+
} else {
12+
const reason = new Error("Mon is not happy");
13+
reject(reason);
14+
}
15+
});
16+
17+
const showOff = phone => {
18+
const message =
19+
"Hey friend, I have a new " +
20+
phone.color +
21+
" " +
22+
phone.brand +
23+
" phone";
24+
return Promise.resolve(message);
25+
};
26+
27+
// call out promise
28+
const askMom = () => {
29+
willIGetNewPhone
30+
.then(showOff)
31+
.then(fullfilled => console.log(fullfilled))
32+
.then(error => console.log(error.message));
33+
};
34+
35+
askMom();
36+
37+
// Same above example with ES-8 async-await
38+
//
39+
// const isMomHappy = true;
40+
41+
// Promise
42+
const willIGetNewPhone = new Promise((resolve, reject) => {
43+
if (isMomHappy) {
44+
const phone = {
45+
brand: "Samsung",
46+
color: "black"
47+
};
48+
resolve(phone);
49+
} else {
50+
const reason = new Error("mom is not happy");
51+
reject(reason);
52+
}
53+
});
54+
55+
// 2nd promise
56+
async function showOff(phone) {
57+
return new Promise((resolve, reject) => {
58+
var message =
59+
"Hey friend, I have a new " +
60+
phone.color +
61+
" " +
62+
phone.brand +
63+
" phone";
64+
65+
resolve(message);
66+
});
67+
}
68+
69+
// call our promise
70+
async function askMom() {
71+
try {
72+
console.log("before asking Mom");
73+
74+
let phone = await willIGetNewPhone;
75+
let message = await showOff(phone);
76+
77+
console.log(message);
78+
console.log("after asking mom");
79+
} catch (error) {
80+
console.log(error.message);
81+
}
82+
}
83+
84+
(async () => {
85+
await askMom();
86+
})();
87+
88+
/*Further Reading -
89+
[https://scotch.io/tutorials/javascript-promises-for-dummies](https://scotch.io/tutorials/javascript-promises-for-dummies)*/

0 commit comments

Comments
 (0)