forked from HackYourFuture/JavaScript3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromises.js
More file actions
68 lines (54 loc) · 1.45 KB
/
promises.js
File metadata and controls
68 lines (54 loc) · 1.45 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
const posts = [
{ title: 'Post One', body: 'This is post one' },
{ title: 'Post Two', body: 'This is post two' },
];
function getPosts() {
setTimeout(() => {
let output = '';
posts.forEach(post => {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
}, 1000);
}
function createPost(post) {
return new Promise((resolve, reject) => {
setTimeout(() => {
posts.push(post);
const error = false;
if (!error) {
resolve();
} else {
reject(new Error('Something went wrong'));
}
}, 2000);
});
}
// createPost({ title: 'Post Three', body: 'This is post three' })
// .then(getPosts)
// .catch(err => console.log(err));
// Async / Await
// async function init() {
// await createPost({ title: 'Post Three', body: 'This is post three' });
// getPosts();
// }
// init();
// Async / Await / Fetch
async function fetchUsers() {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await res.json();
console.log(data);
}
fetchUsers();
// Promise.all
// const promise1 = Promise.resolve('Hello World');
// const promise2 = 10;
// const promise3 = new Promise((resolve, reject) =>
// setTimeout(resolve, 2000, 'Goodbye')
// );
// const promise4 = fetch('https://jsonplaceholder.typicode.com/users').then(res =>
// res.json()
// );
// Promise.all([promise1, promise2, promise3, promise4]).then(values =>
// console.log(values)
// );