Skip to content

Instantly share code, notes, and snippets.

@rbrahul
Created September 2, 2017 14:13
Show Gist options
  • Save rbrahul/6e2e6cbe418336b49167aa467bd81438 to your computer and use it in GitHub Desktop.
Save rbrahul/6e2e6cbe418336b49167aa467bd81438 to your computer and use it in GitHub Desktop.
Async and Await example using Github Api
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