簡體   English   中英

異步/等待,數據獲取和未解決的承諾

[英]async/await, data fetching, and unresolved promises

我正在處理的Node.js應用程序中遇到問題,似乎找不到解決方案。

我正在使用GitHub API來:

  1. 從給定用戶獲取存儲庫
  2. 提取每個檢索到的存儲庫的問題
  3. 將數據整合到一個“回購”對象中

步驟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.allawait承諾:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM