-
Notifications
You must be signed in to change notification settings - Fork 0
/
replace_promise.js
79 lines (62 loc) · 1.83 KB
/
replace_promise.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
78
console.log('Before');
getUser(1, (user) => {
getRepositories(user.githubUsername, (repos) => {
getCommits(repos[0], (commits) => {
console.log(commits);
})
})
});
console.log('After');
function getUser(id) {
return new Promise((resolve, reject) => {
// kick off some async work
setTimeout(() => {
console.log('reading a user from a database');
resolve({ id: id, githubUsername: 'nasim'});
}, 2000);
});
}
function getRepositories(username) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('calling github api...');
resolve(['repo1', 'repo2', 'repo3']);
}, 2000);
});
}
function getCommits(repo) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('calling github api...');
resolve(['repo1', 'repo2', 'repo3']);
}, 2000);
});
}
// -------------------- Previous Nested Callback hell
// console.log('Before');
// getUser(1, (user) => {
// getRepositories(user.githubUsername, (repos) => {
// getCommits(repos[0], (commits) => {
// console.log(commits);
// });
// });
// });
// console.log('After');
// function getUser(id, callback) {
// setTimeout(() => {
// console.log('reading a user from a database');
// callback({ id: id, githubUsername: 'nasim'});
// }, 2000);
// }
// function getRepositories(username, callback) {
// setTimeout(() => {
// console.log('calling github api...');
// callback(['repo1', 'repo2', 'repo3']);
// }, 2000);
// }
// function getCommits(repo, callback) {
// setTimeout(() => {
// console.log('calling github api...');
// callback(['repo1', 'repo2', 'repo3']);
// }, 2000);
// }