-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromises.js
77 lines (59 loc) · 1.88 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
67
68
69
70
71
72
73
74
75
76
77
const posts=[
{title: 'post one', body: 'this is post one',activityTime:new Date().getTime()},
{title: 'post two', body: 'this is post two',activityTime:new Date().getTime()}
]
function getdata(){
setTimeout(() => {
let data="";
posts.forEach((value)=>{
data+=`<li>${value.title} Last seen at ${parseInt((new Date().getTime()- value.activityTime)/1000)} sec</li>`;
});
document.body.innerHTML=data;
}, 2000);
}
//promises
function createpost(obj){
return new Promise((resolve,reject)=>{
setTimeout(() => {
let time=new Date().getTime();
const error=false;
if(!error){
resolve(posts.push({...obj,activityTime:time}));
}
else{reject();}
}, 2000);
})
}
function delete_post(){
return new Promise((resolve, reject) => {
setTimeout(() => {
const arr=posts.length;
if(arr){
posts.pop()
resolve();
}else{reject('Array is empty')}
}, 1000);
})
}
//console.log(posts);
createpost({title:'post three',body:'this is post three'})
.then(()=>{
getdata();
delete_post().then(getdata)
.catch((error)=>console.log(error));
createpost({title: 'post four',body:'this is post four'})
.then(getdata)
.catch((error)=>{console.log(error)})
createpost({title: 'post five',body:'this is post five'})
.then(getdata)
.catch((error)=>{console.log(error)})
})
.catch(()=>{console.log("something went wrong")});
//delete_post().then(getdata)
//.catch((error)=>{console.log(error)});
//createpost({title: 'post four',body:'this is post four'})
//.then(getdata)
//.catch((error)=>{console.log(error)})
//createpost({title: 'post five',body:'this is post five'})
//.then(getdata)
//.catch((error)=>{console.log(error)})