Created
September 2, 2017 14:13
-
-
Save rbrahul/6e2e6cbe418336b49167aa467bd81438 to your computer and use it in GitHub Desktop.
Async and Await example using Github Api
This file contains 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
const fetch = require("node-fetch"); | |
const fs = require('fs'); | |
function getAllRepos() { | |
return fetch('https://api.github.com/users/rbrahul/repos'); | |
} | |
function getRepoInfo(repoName) { | |
return fetch(`https://api.github.com/repos/rbrahul/${repoName}`); | |
} | |
async function fetchAllRepos() { | |
try { | |
const response = await getAllRepos(); | |
return response.json(); | |
} | |
catch (e) { | |
console.log("Error found", e.message); | |
throw e; | |
} | |
} | |
async function fetchRepoData(repoName) { | |
try { | |
const repo = await getRepoInfo(repoName); | |
return repo.json(); | |
} | |
catch (e) { | |
console.log("Error found", e.message); | |
throw e; | |
} | |
} | |
(async function () { | |
try { | |
const allrepos = await fetchAllRepos(); | |
const repo = await fetchRepoData(allrepos[0].name); | |
const data = Object.assign({}, { repositories: allrepos }, { firstRepository: repo }); | |
fs.writeFileSync('./reponse.json', JSON.stringify(data, null, 2)); | |
console.log('Response saved to file') | |
} catch (e) { | |
console.log(e); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment