-
Notifications
You must be signed in to change notification settings - Fork 0
/
promises.js
66 lines (54 loc) · 1.42 KB
/
promises.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
const posts = [
{ title: 'Post One', body: 'This is post one' },
{ title: 'Post Two', body: 'This is post two' },
];
function getPosts() {
setTimeout(function () {
let output = '';
posts.forEach(function (post, index) {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
}, 1000);
}
function createPost(post) {
return new Promise((resolve, reject) => {
setTimeout(function () {
posts.push(post);
const error = false;
if (!error) {
resolve();
} else {
reject('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 with 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)
);