Created
October 18, 2018 05:23
-
-
Save salmanx/4ecfddb11469a1e653a9ba9539bc5ed2 to your computer and use it in GitHub Desktop.
an example for callback to promise conversion in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log('Before'); | |
// callback approach | |
// getUser(1, displayUser); | |
// promised based approach | |
// getUser(1) | |
// .then(user => getRepositories(user.name)) | |
// .then(repos => getCommits(repos[0])) | |
// .then(commits => console.log(commits)) | |
// .catch(err => console.log(err)); | |
// async-await approach | |
async function displayUserCommits(){ | |
try { | |
const user = await getUser(1); | |
const repos = await getRepositories(user.name); | |
const commits = await getCommits(repos[0]); | |
console.log(commits); | |
} | |
catch(err){ | |
console.log(err); | |
} | |
} | |
displayUserCommits(); | |
console.log("After"); | |
function getUser(id){ | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
console.log("Reading a user from database!"); | |
resolve({ id: id, name: "salmanx" }); | |
}, 2000) | |
}) | |
} | |
function getRepositories(username){ | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
console.log("Calling github api for repo"); | |
resolve(["repo1", "repo2", "repo3"]); | |
}, 2000) | |
}) | |
} | |
function getCommits(repo){ | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
console.log("Calling github api for commits"); | |
resolve(["commit1", "commit2"]); | |
}, 2000) | |
}) | |
} | |
function displayCommits(commits){ | |
console.log(commits); | |
} | |
function displayRepos(repos){ | |
getCommits(repos[0], displayCommits); | |
} | |
function displayUser(user){ | |
getRepositories(user.name, displayRepos) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment