Javascript从异步函数向数组添加值不会等到完成

时间:2019-01-19 13:44:43

标签: javascript arrays asynchronous async-await

我有一个javascript函数,可从GitLab和GitHub API获取一些数据。此数据需要合并在一起并进行排序。

我的问题是,我总是得到一个空的searchResults数组。我不知道如何等待,直到所有结果输入到数组中。

async function searchCode(){
var gitlab = document.getElementById("input.gitlab.activation").checked;
var gitlab_accesstoken = document.getElementById("input.gitlab.token").value;
var github = document.getElementById("input.github.activation").checked;
var github_accesstoken = document.getElementById("input.github.token").value;
var searchTerm = document.getElementById("searchterm").value;

var searchResults = [];

if(gitlab){
    var uri = `https://gitlab.com/api/v4/projects?search=${searchTerm}&order_by=last_activity_at&private_token=${gitlab_accesstoken}&per_page=10`;
    const reposResponse = await fetch(uri);
    const repos = await reposResponse.json();

    repos.forEach(async function(element){
        var contributorsResponse = await fetch(`${element._links.members}?private_token=${gitlab_accesstoken}`);
        const contributors = await contributorsResponse.json();
        var result = {
            name: `<a href=\"${element.web_url}\" target=\"_blank\">` + element.name + '</a>',
            description: element.description,
            source: 'GitLab',
            lastUpdate: new Date(element.last_activity_at).toLocaleString('de-DE'),
            contributors: contributors.length,
            homepage: ''
        };

        searchResults.push(result);

    });
}

if(github){
    var uri = `https://api.github.com/search/repositories?access_token=${github_accesstoken}&q=${searchTerm}+in:description&sort=updated&per_page=10`;
    const reposResponse = await fetch(uri);
    const repos = await reposResponse.json();

    repos.items.forEach(async function(element){
        const contributorsResponse = await fetch(`${element.contributors_url}?access_token=${github_accesstoken}`);
        const contributors = await contributorsResponse.json();

        var result = {
            name: `<a href=\"${element.html_url}\" target=\"_blank\">` + element.name + '</a>',
            description: element.description,
            source: 'GitHub',
            lastUpdate: new Date(element.updated_at).toLocaleString('de-DE'),
            contributors: contributors.length,
            homepage: `<a href=\"${element.homepage}\" target=\"_blank\">` + element.homepage + '</a>'
        };

        searchResults.push(result);

    });
}

console.log(searchResults); //always shows an empty array in the console and evaluates the data afterwards

Promise.all([searchResults]).then(values => {
    console.log(values[0][0]); //shows undefined 
});

addResultToTable(searchResults);

}

0 个答案:

没有答案