Reputation: 1110
I'm running into an issue in an nodejs application I'm working on and can't seem to find a solution.
I'm working with the GitHub API to:
Step 3 is where problems arise.
I'm working with two async functions,getReposForUser()
and getIssuesForRepo()
, which behave as follows
async function getReposForUser(username) {
// Fetch user repos from GitHub
var result = await github.repos.getForUser({
username: username,
per_page: 100
})
// Grab issues for each repo
repos = repos.map(repo => {
return getIssuesForRepo(repo);
});
// console.log(repos);
}
async function getIssuesForRepo(repo) {
/*
if there are issues available, fetch them and attach
them to the repo object (under a property named issues).
otherwise, assign the issues property a value of null
*/
if (repo.has_issues) {
let issues = await github.issues.getForRepo({
owner: repo.owner.login,
repo: repo.name,
state: 'open'
});
repo.issues = issues;
return repo;
} else {
return repo.issues = null;
}
}
When I try to console.log(repos)
after getIssuesForRepo()
runs, I get an array of Promises. After doing some research, it's become clear that async/await functions return Promises. Ok, got that. My question is, what can I do in order to create a new array of objects with the resolved value of those promises? Basically, I want to attach the array of issues retrieved for each repo to its respective repo.
Thanks in advance to anyone who might help.
Also, why does this work inside getReposForUser()
after getIssuesForRepo()
runs?
let firsRepo = await getIssuesForRepo(repos[0]);
console.log(firsRepo);
In this case, I actually see the object, not the unresolved promise...
Upvotes: 1
Views: 722
Reputation: 1075139
what can I do in order to create a new array of objects with the resolved value of those promises?
await
Promise.all
on the array of promises:
repos = await Promise.all(repos.map(repo => {
return getIssuesForRepo(repo);
}));
Side note: Your map
callback can just be getIssuesForRepo
:
repos = await Promise.all(repos.map(getIssuesForRepo));
map
calls its callback with the entry, its index, and the array being mapped. Since your getIssuesforRepo
only uses its first argument, the extra two will be ignored.
Upvotes: 4