Skip to content

Commit 72a092d

Browse files
Promises in javascript
1 parent 108f485 commit 72a092d

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

promises/index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,6 @@
77
</head>
88
<body>
99

10-
<script src="./app.js"></script>
10+
<script src="./script.js"></script>
1111
</body>
1212
</html>

promises/script.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
const posts = [
2+
{title:"Post one",body:"This is post one"},
3+
{title:"Post two",body:"This is post two"}
4+
]
5+
6+
function getPosts(){
7+
setTimeout(()=>{
8+
let output = "";
9+
posts.forEach((post,index)=>{
10+
output += `<li>${post.title}</li>`;
11+
});
12+
document.body.innerHTML = output
13+
},1000);
14+
}
15+
16+
function createPost(post){
17+
return new Promise((res,rej)=>{
18+
setTimeout(()=>{
19+
posts.push(post)
20+
21+
const error = false;
22+
23+
if(!error){
24+
res();
25+
}
26+
else{
27+
rej(`Error something went wrong`);
28+
}
29+
},2000)
30+
})
31+
}
32+
// createPost({title:"Post three",body:"This is post three"}).then(getPosts).catch((err)=>console.log(err));
33+
34+
//Promise.all
35+
36+
const promise1 = Promise.resolve("Hello world");
37+
const promise2 = 10;
38+
const promise3 = new Promise((res,rej)=>
39+
setTimeout(res,2000,"Goodbye")
40+
)
41+
42+
const promise4 = fetch(`https://jsonplaceholder.typicode.com/posts`)
43+
44+
const promise5 = fetch(`https://jsonplaceholder.typicode.com/posts`).then(res=>res.json())
45+
Promise.all([promise1,promise2,promise3,promise4,promise5]).then(values=>console.log(values))

0 commit comments

Comments
 (0)