forked from codegym-vn/typescript-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise.ts
186 lines (166 loc) · 3.87 KB
/
promise.ts
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import './scss/styles.scss';
const wait5Secs = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(5);
}, 5000);
});
wait5Secs.then(data => console.log(data)).catch(err => console.error(err));
function httpGet(url: string): Promise<any> {
return new Promise(function(resolve, reject) {
const request = new XMLHttpRequest();
request.onload = function() {
if (this.status === 200) {
// Success
resolve(this.response);
} else {
// Something went wrong (404 etc.)
reject(new Error(this.statusText));
}
};
request.onerror = function() {
reject(new Error('XMLHttpRequest Error: ' + this.statusText));
};
request.open('GET', url);
request.send();
});
}
httpGet('https://api.github.com/search/repositories?q=angular').then(
function(value) {
console.log('Contents: ' + value);
},
function(reason) {
console.error('Something went wrong', reason);
}
);
// parseJSON
function parseResponse(value: string) {
try {
return JSON.parse(value);
} catch (_) {
return value;
}
}
httpGet('https://api.github.com/search/repositories?q=angular')
.then(parseResponse)
.then(data => console.log(data))
.catch(function(reason) {
console.error('Something went wrong', reason);
});
// promise chỉ resolve hoặc reject duy nhất 1 lần
const promise = new Promise((resolve, reject) => {
resolve('done');
reject(new Error('…')); // ignored
setTimeout(() => resolve('…')); // ignored
});
promise.then(data => console.log(data));
/**
* Async/Await
*/
async function f() {
return 1;
}
function fp() {
return Promise.resolve(1);
}
f().then(data => console.log('async fn', data));
(async() => {
const data = await fp();
console.log('async/await', data);
})();
async function fns() {
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
// wait till the promise resolves (*)
const result = await promise;
console.log(result); // "done!"
}
fns();
// handle error
async function getUser(username: string) {
try {
const response = await fetch(
`https://api.github.com/search/users?q=${username}`
);
return await response.json();
} catch (e) {
throw e;
}
}
getUser('bob')
.then(res => console.log(res))
.catch(err => console.warn(err));
// do not combine sync operations with async/await
(() => {
let x = 0;
async function r5() {
x += 1;
console.log(x);
return 5;
}
(async () => {
x += await r5();
console.log(x);
})();
})();
// fixed version
(() => {
let x = 0;
async function r5() {
x += 1;
console.log(x);
return 5;
}
(async () => {
const y = await r5();
x += y;
console.log(x);
})();
})();
// Too Sequential
async function fetchAllBook() {
await new Promise(resolve => {
console.log('Waiting 2s...');
setTimeout(() => resolve(), 2000);
});
console.log('fetchAllBook');
return [
{
id: 'book-id-1',
authorId: 'author-id-1'
}, {
id: 'book-id-2',
authorId: 'author-id-2'
}, {
id: 'book-id-3',
authorId: 'author-id-3'
}
];
}
async function fetchAuthorById(authorId: string) {
console.log('fetchAuthorById');
return {
authorId,
};
}
async function getBooksAndAuthor(authorId: string) {
const books = await fetchAllBook();
const author = await fetchAuthorById(authorId);
return {
author,
books: books.filter(book => book.authorId === authorId),
};
}
getBooksAndAuthor('author-id-2');
// Too Sequential fixed
async function getBooksAndAuthorFixed(authorId: string) {
const bookPromise = fetchAllBook();
const authorPromise = fetchAuthorById(authorId);
const books = await bookPromise;
const author = await authorPromise;
return {
author,
books: books.filter(book => book.authorId === authorId),
};
}
getBooksAndAuthorFixed('author-id-2');