It seems like my promises
are not completing as expected due to incorrect handling. When using Promise.all()
, the final result displayed with console.log(payload)
is {}
. Ideally, it should show something similar to this:
{
project1: {
description: '...',
stats: {python: 50, css: 50}
},
project2: {
description: '...',
stats: {python: 25, css: 75}
},
project3: {
description: '...',
stats: {python: 10, css: 90}
}
}
Here's the code snippet in question:
app.get("/github", (req, res) => {
const authorizationHeader = {headers: {Authorization: 'Basic ' + keys.github.accessToken}};
const user = 'liondancer';
const githubEndpoint = 'api.github.com/repos/';
var payload = {};
let promises = req.query.projects.map(project => {
let datum = {};
const githubAPIUrl = path.join(githubEndpoint, user, project);
return fetch('https://' + githubAPIUrl + '/languages', authorizationHeader).then(res => {
// Get Languages of a project
if (!isStatus2XX(res)) {
throw 'Status code not 2XX:' + res.status;
}
return res.json();
}).then(res => {
let languagePercentages = {};
let total = 0;
// get total
Object.keys(res).forEach(key => {
total += Number.parseInt(res[key]);
});
// compute percentages
Object.keys(res).forEach(key => {
languagePercentages[key] = (Number.parseInt(res[key]) / total * 100).toFixed(1);
});
datum.stats = languagePercentages;
// Get description of a project
fetch('https://' + githubAPIUrl).then(res => {
if (!isStatus2XX(res)) {
throw 'Status code not 2XX: ' + res.status;
}
return res.json();
}).then(res => {
datum.description = res.description;
payload[project] = datum;
});
}).catch(err => {
console.log('Github API error: ' + err);
});
});
Promise.all(promises).then(() => {
console.log(payload);
res.send(payload);
}).catch(err => {
console.log('nothing ever works...: ' + err);
});
});
Initially, changing .map
to .forEach()
seemed to make the code work correctly and payload
had the anticipated values. However, when trying to send the collected results, I encountered difficulties executing the promises in the correct order, or at all.