处理链式和内部承诺没有正确执行

时间:2016-12-14 06:55:58

标签: javascript express asynchronous promise ecmascript-6

我相信我的promises没有完成,因为我没有正确处理它们。在我的代码末尾,在Promise.all()内,console.log(payload)正在显示{}。当它应该显示如下:

{
  project1: {
    description: '...',
    stats: {python: 50, css: 50}
  },
    project2: {
    description: '...',
    stats: {python: 25, css: 75}
  },
  project3: {
    description: '...',
    stats: {python: 10, css: 90}
  }
}

代码:

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);
    });
});

首先,我将.map替换为.forEach()以使代码执行,代码似乎已正常运行。 payload具有我期望的值。但是,现在我想发送聚合结果,我似乎无法以正确的顺序正确执行承诺,或者根本不执行。

1 个答案:

答案 0 :(得分:1)

只需更改此行

fetch('https://' + githubAPIUrl).then(res => {

进入这个

return fetch('https://' + githubAPIUrl).then(res => {

所以promise.all将在所有嵌套的promise都已解决后解析,因此填充了有效负载。