-
Notifications
You must be signed in to change notification settings - Fork 0
/
async-await-vs-promise.js
36 lines (31 loc) · 1.03 KB
/
async-await-vs-promise.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
// "a/a" vs "p/t/c"
tryAsyncAwait();
tryPromise();
tryPromiseMoreRealistically();
async function tryAsyncAwait() {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/");
const json = await response.json();
console.log(json.map((x) => x.title));
// note: canNOT do await fetch(...).json();
}
function tryPromise() {
fetch("https://jsonplaceholder.typicode.com/todos/")
.then((response) => response.json())
.then((data) => console.log(data.map((x) => x.title)))
.catch((err) => console.log(err));
// downside: you're already nesting things inside .then
}
function tryPromiseMoreRealistically() {
const promise = new Promise((resolve, reject) => {
exampleApiRequest(resolve, reject);
});
promise
.then((response) => response.json())
.then((data) => console.log(data.map((x) => x.title)));
// downside: you're already nesting things inside .then
}
function exampleApiRequest(resolve, reject) {
fetch("https://jsonplaceholder.typicode.com/todos/")
.then(resolve)
.catch(reject);
}