Skip to content

Instantly share code, notes, and snippets.

@dani8art

dani8art/promise-each.js

Last active Sep 12, 2017
Embed
What would you like to do?
'use strict';
var request = require("request"),
Promise = require('bluebird');
var token = process.env.GITHUB_TOKEN;
function gh(url, callback) {
//err response body
request({
url: url,
json: true, headers: {
'User-Agent': 'js-tutorial'
},
'auth': {
'user': 'dani8art',
'pass': token
}
}, callback);
return true;
}
function getAllRepos() {
var url = "https://api.github.com/users/dani8art/repos";
return new Promise((resolve, reject) => {
gh(url, (err, response, body) => {
if (err) {
reject(err);
} else {
resolve(body);
}
});
});
}
function getRepoByName(name) {
return new Promise((resolve, reject) => {
console.log("launched promise " + name);
gh("https://api.github.com/repos/dani8art/" + name, (err, response, body) => {
if (err) {
reject(err);
} else {
console.log("resolved " + body.name);
resolve(body);
}
});
});
}
getAllRepos().then(repos => {
console.log(repos);
var promises = [];
repos.forEach(function (element) {
promises.push(getRepoByName(element.name));
});
var sequentialResults = [];
Promise.each(repos, (repo, i) => {
return getRepoByName(repo.name).then((body) => {
console.log("Body name: " + body.name);
body.idx = i;
sequentialResults.push(body);
}).catch((err) => {
if (err) throw new Error('Error getting repo ' + repo.name + "" + err.toString())
});
}).then(() => {
console.log(sequentialResults)
console.log("Ended.");
}).catch((err) => {
if (err) throw new Error('Error getting repo by name ' + err.toString())
});
var processingSequentialResults = [];
Promise.each(promises, (body) => {
console.log("each then name: " + body.name);
processingSequentialResults.push(body);
}).then(() => {
console.log("Ended.");
}).catch((err) => {
if (err) throw new Error('Error getting repo by name ' + err.toString())
});
Promise.all(promises).then((results) => {
console.log(results);
console.log("Ended.");
}).catch((err) => {
if (err) throw new Error('Error getting repo by name ' + err.toString())
});
}).catch(err => {
if (err) throw new Error('Error requesting all repos, ' + err.toString())
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.