forked from wesbos/beginner-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync-await-error-handling-FINISHED.html
64 lines (53 loc) · 1.55 KB
/
async-await-error-handling-FINISHED.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Async Await</title>
<link rel="stylesheet" href="../base.css">
</head>
<body>
<script>
function wait(ms = 0) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
})
}
function makePizza(toppings = []) {
return new Promise(function (resolve, reject) {
// reject if people try with pineapple
if (toppings.includes('pineapple')) {
reject('Seriously? Get out 🍍');
}
const amountOfTimeToBake = 500 + (toppings.length * 200);
// wait 1 second for the pizza to cook:
setTimeout(function () {
// when you are ready, you can resolve this promise
resolve(`Here is your pizza 🍕 with the toppings ${toppings.join(' ')}`);
}, amountOfTimeToBake);
// if something went wrong, we can reject this promise;
});
}
function handleError(err) {
console.log('ohhh noooo');
console.log(err);
}
function handleDisgustingPizza() {
}
async function go() {
const pizza = await makePizza(['pineapple']).catch(handleDisgustingPizza);
return pizza;
}
// catch it at run time
go().catch(handleError);
// make a safe function with a HOF
function makeSafe(fn, errorHandler) {
return function () {
fn().catch(errorHandler)
}
}
const safeGo = makeSafe(go, handleError);
safeGo();
</script>
</body>
</html>