-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchain-of-promises.html
56 lines (51 loc) · 2.08 KB
/
chain-of-promises.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
<!DOCTYPE html>
<html>
<head>
<title>Promises</title>
</head>
<body>
<button id="longPromiseChain">Start long promise chain</button>
<button id="shortPromiseChain">Start short promise chain</button>
<script>
document.querySelector('#longPromiseChain').addEventListener('click', () => {
console.log('Button clicked');
test().then((value) => {
console.log(`Value 1: ${value}`); // No onRejected callback, internally replaced with a "Thrower"
}).then((value) => {
console.log(`Value 2: ${value}`);
}, (reason) => {
console.log(`Reason 2: ${reason}`);
}).then((value) => {
console.log(`Value 3: ${value}`);
}, (reason) => {
console.log(`Reason 3: ${reason}`);
}).catch((reason) => {
console.log(`Prototype.catch: ${reason}`); // catch() behaves the same as then(undefined, onRejected)
}).finally(() => {
console.log('Prototype.finally');
});
});
document.querySelector('#shortPromiseChain').addEventListener('click', () => {
console.log('Button clicked');
test().then((value) => {
console.log(`Value 1: ${value}`); // No onRejected callback, internally replaced with a "Thrower"
}).catch((reason) => {
console.log(`Prototype.catch: ${reason}`); // catch() behaves the same as then(undefined, onRejected)
}).finally(() => {
console.log('Prototype.finally');
});
});
async function test() {
try {
// const result = await new Promise((resolve, reject) => resolve(10));
const result = await new Promise((resolve, reject) => reject('Horrible error!'));
console.log(`Promise result: ${result}`);
return result;
} catch (error) {
console.log(`Catch: ${error}`);
throw error;
}
}
</script>
</body>
</html>