-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasync.js
More file actions
83 lines (59 loc) · 2.07 KB
/
async.js
File metadata and controls
83 lines (59 loc) · 2.07 KB
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
75
76
77
78
79
80
81
82
83
const fs = require('fs');
// traditional callbacks
fs.readFile('./async.js', (err, data) => {
if (err) {
console.error(err);
process.exit(1);
} else {
doSomethingWithData(data);
}
});
// promises
fs.promises.readFile('./async.js').then(doSomethingWithData).catch(e => {
console.error(e);
process.exit(1);
});
// async/await
async function getFile() {
try {
const data = await fs.promises.readFile('./async.js');
doSomethingWithData(data);
} catch (e) {
console.error(e);
process.exit(1);
}
}
////////////////////////////////////////////////////////////////
// fetch
fetch('/api/my/api/url/123').then(res => {
if (!res.ok) {
throw new Error('Error during request');
}
return res.json();
}).then(doSomethingWithJSON).catch(doSomethingWithError);
// async/await fetch
async function getJSON() {
const res = await fetch('/api/my/api/url/123');
if (!res.ok) {
return doSomethingWithError(new Error('Error during request'));
}
const json = await res.json();
doSomethingWithJSON(json);
}
// traditional request -- don't do this, just showing how far things have come
function fetchGetOld(url) {
const request = new XMLHttpRequest();
request.addEventListener('load', function() {
doSomethingWithJSON(JSON.parse(this.responseText));
});
request.open('GET', url);
request.send();
}
//////////////////////////////////////////////////////////////////////
// utilities
Promise.resolve(value); // immediately resolves a promise with a value
Promise.reject(error); // immediately rejects a promise with a value
Promise.all([promise1, promise2]); // resolves with an ordered array of responses when all promises passed are resolved
Promise.allSettled([promise1, promise2]); // resolves with an ordered array of the resolved OR rejected values of each promise
Promise.any([promise1, promise2]); // resolves with the value of this first promise to resolve, i.e. whichever promise is faster
Promise.race([promise1, promise2]); // resolves with the value of this first promise to resolve OR reject, i.e. whichever promise is faster