forked from daurham/async_practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1_asyncProgramming.js
74 lines (56 loc) · 1.57 KB
/
1_asyncProgramming.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
/*
There are 3 main ways to handle async programming
1). Callbacks
2). Promises
3). Async / Await
- Each is an upgrade of its predicessor
- Many packages and libraries will use a form of async functionality to perform a task.
- Learn to use the fundemental of each
*/
const axios = require('axios');
const Promise = require('bluebird');
const fs = require('fs');
const db = {query: () => {}}; // assume we're requiring a db's connection obj
// Async Callbacks:
let cb1 = setTimeout(function () {
console.log('async task');
}, 1000);
// cb1();
let cb2 = setTimeout(() => console.log('async task'), 1000);
// cb2()
// Error First Callbacks:
let cb3 = fs.readFile('file.txt', (err, result) => {
if (err) {
// handle err
} else {
// handle result
}
});
let cb4 = db.query('SELECT * FROM movies', (err, res) => {
if (err) {
// handle err
} else {
// handle result
}
});
// Promises:
/* Promises consist of 2 phases and 3 states (pending, fulfilled & rejected)
Phase 1: Promise Setup - Defines what constitutes a "fullfilled" or "failed"
Phase 2: Promise Object - Enables flow control handling of "fullfilled" & "failed" scenarios
*/
// Setup
let aPromise = new Promise(function(resolve, reject) {
let conditionIsTruthy_Or_didAsyncTask = true;
if (conditionIsTruthy_Or_didAsyncTask) {
resolve('async value');
} else {
reject('err');
}
})
let aPromise2 = new Promise((resolve) => resolve(''));
// Promise Object
aPromise
.then((res) => console.log('fulfilled'))
.catch((err) => console.log('failed'));
aPromise2
.then(() => console.log())