-
Notifications
You must be signed in to change notification settings - Fork 0
/
promises.js
39 lines (32 loc) · 855 Bytes
/
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
const posts = [
{ title: 'Post one', body: 'This is post one' },
{ title: 'Post two', body: 'This is post two' }
];
function createPost(post) {
return new Promise((resolve, reject) => {
setTimeout(function() {
posts.push(post);
const err = Math.random() < 0.5;
if (err) {
reject('Something went wrong!');
} else {
resolve();
}
}, 2000);
});
}
function getPosts() {
setTimeout(() => {
let output = '';
posts.forEach((post, index) => {
output += `<div>${post.title}</div>`;
});
document.body.innerHTML = output;
}, 1000);
}
getPosts();
createPost({ title: 'Post three', body: 'This is post three' })
.then(getPosts)
.catch(err => {
console.log(err);
});