[英]async/await, data fetching, and unresolved promises
我正在處理的Node.js應用程序中遇到問題,似乎找不到解決方案。
我正在使用GitHub API來:
步驟3是出現問題的地方。 我正在使用兩個異步函數getReposForUser()
和getIssuesForRepo()
,它們的行為如下
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;
}
}
當我在getIssuesForRepo()
運行之后嘗試console.log(repos)
,得到了一個Promises數組。 經過研究后,很明顯,異步/等待功能會返回Promises。 好,知道了 我的問題是, 我該怎么做才能創建具有這些承諾的已解決價值的新對象數組? 基本上,我想將為每個存儲庫檢索的問題數組附加到其各自的存儲庫。
預先感謝任何可能提供幫助的人。
另外,為什么在運行getReposForUser()
之后在getIssuesForRepo()
內部工作?
let firsRepo = await getIssuesForRepo(repos[0]);
console.log(firsRepo);
在這種情況下,我實際上看到的是對象,而不是未解決的承諾。
為了用這些promise的解析值創建一個新的對象數組,我該怎么做?
await
Promise.all
上await
承諾:
repos = await Promise.all(repos.map(repo => {
return getIssuesForRepo(repo);
}));
附注:您的map
回調可能只是 getIssuesForRepo
:
repos = await Promise.all(repos.map(getIssuesForRepo));
map
使用條目,索引和要映射的數組調用其回調。 由於您的getIssuesforRepo
僅使用其第一個參數,因此多余的兩個將被忽略。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.