JavaScript - Async - Generation 2 - Promises

From
https://www.joshwcomeau.com/javascript/promises/

After problems with Callbacks were determined, a version 2 technology was released and called Promises.

Sample code

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
<html>
<head>
<meta charset="utf-8">
<title>JavaScript - Async - Level 2 - Promises</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="JavaScript - Async - Level 2 - Promises">
</head>
<body>
<h1>JavaScript - Async - Level 2 - Promises</h1>

<script>
// Run JavaScript after the DOM is fully loaded
document.addEventListener('DOMContentLoaded', function () {
console.log('DOM fully loaded and parsed.');
// Your script logic here

console.log('Start');

console.log('3');
wait(1000)
.then(() => {
console.log('2');
return wait(1000);
})
.then(() => {
console.log('1');
return wait(1000);
})
.then(() => {
console.log('Happy New Year!!');
});

// end of event listener
});


function wait(duration) {
return new Promise((resolve) => {
setTimeout(
() => resolve(),
duration
);
});
}

</script>
</body>
</html>

Promises introduce the concept of chaining, infact the example above shows chaining multiple promises.

Promises terminology

Promises are always in one of three possible states: pending, fulfilled, and rejected.

Creating your own promise

Here is an example of creating your own promise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function getUser(userId) {
return new Promise((resolve) => {
// The asynchronous work, in this case, is
// looking up a user from their ID
db.get({ id: userId }, (user) => {
// Now that we have the full user object,
// we can pass it in here...
resolve(user);
});
});
}

getUser('abc123').then((user) => {
// ...and pluck it out here!
console.log(user);
// { name: 'Josh', ... }
})

the Response object.

If the code runs to completion it returns a positive object, But there could be an error.

Checkout this response object

1
2
3
4
5
Response {
ok: false,
status: 404,
statusText: 'Not Found',
}

error handling

1
2
3
4
5
6
7
fetch('/api/get-data')
.then((response) => {
// ...
})
.catch((error) => {
console.error(error);
});

reject

1
2
3
4
5
6
7
8
9
new Promise((resolve, reject) => {
someAsynchronousWork((result, error) => {
if (error) {
reject(error);
return;
}
resolve(result);
});
});

The reject statement will mark the promise as rejected.