-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise2.js
52 lines (43 loc) · 1.28 KB
/
promise2.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
// Using promises instead of callback function
console.log('Before');
// Using Callback function
/*
getUser(1, (user) => {
getRepositories(user.gitHubUsername, (repos) => {
getCommits(repos[0], (commits) => {
console.log(commits);
})
})
});
*/
// Using promises instead of callback function (catch error as a best practice)
getUser(1)
.then(user => getRepositories(user.gitHubUsername))
.then(repos => getCommits(repos[0]))
.then(commits => console.log('Commits ' + commits))
.catch(err => console.log(err.message));
console.log('After');
function getUser(id) {
return new Promise(function (resolve, reject) {
setTimeout(() => {
console.log('Reading a user from a database...');
resolve({ id: id, gitHubUsername: 'mosh' });
}, 2000);
})
}
function getRepositories(username) {
return new Promise(function (resolve, reject) {
setTimeout(() => {
console.log('Calling GitHub API...');
resolve(['repo1', 'repo2', 'repo3']);
}, 2000);
})
}
function getCommits(repo) {
return new Promise(function (resolve, reject) {
setTimeout(() => {
console.log('Calling GitHub API...');
resolve(['commit']);
}, 2000);
})
}