-
Notifications
You must be signed in to change notification settings - Fork 0
/
Function-With-vs-Without-Callback-2.js
77 lines (58 loc) · 1.59 KB
/
Function-With-vs-Without-Callback-2.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
// 1. Without Callback
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);
}
//digunakan setTimeout untuk menirukan (mimic) proses delay akibat javascript berkomunikasi dengan server
function createPost(post) {
setTimeout(() => {
posts.push(post);
}, 2000);
}
createPost({title: 'Post Three', body: 'This is post three.'});
getPosts();
// Outputnya:
// Logged after 1000 ms:
// Post One
// Post Two
//Post Three tidak muncul karena ketika Post Three dibuat melalui fungsi createPost (2000 ms), proses menulis/menampilkan posts sudah terlebih dahulu terjadi (1000ms). Untuk menangani ini digunakan callback seperti di bawah ini.
// 2. With Callback
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) {
setTimeout(() => {
posts.push(post);
callback();
}, 2000);
}
createPost({title: 'Post Three', body: 'This is post three.'}, getPosts);
getPosts();
// Outputnya:
// * Logged after 1000 ms:
// Post One
// Post Two
// * Logged after 2000 ms:
// Post One
// Post Two
// Post Three
// Post Three muncul karena adanya callback