-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromises.js
58 lines (51 loc) · 1.22 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
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, index) => {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
}, 1000);
}
function createPost(post, callback) {
return new Promise((resolve, reject) => {
setTimeout(() => {
posts.push(post);
const error = false;
if (!error) {
resolve();
} else {
reject("Error: Something went wrong");
}
}, 2000);
});
}
getPosts();
createPost({
title: 'Post Three',
body: 'This is post three'
}).then(getPosts);
const promise1 = Promise.resolve('Hello, World!');
const promise2 = 10;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 2000, "Goodbye, World!");
});
const promise4 = fetch('https://jsonplaceholder.typicode.com/posts/1').then(response => response.json());
Promise.all([
promise1,
promise2,
promise3,
promise4
]).then(values => {
console.log(values);
});