2016-12-14 79 views
0

我相信我的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()有代碼執行,似乎該代碼已經工作正常。​​具有我期望的值。但是,現在我想發送彙總結果,我似乎無法正確地按照正確的順序執行承諾,或者根本沒有。

+0

由於您的'req.query.projects.map(...)'回調函數沒有返回值,因此您將得到一個'undefined'值。您需要「返回」您正在創建的承諾(即'return fetch(...)'),以便獲得一組承諾。 –

+0

@FelixKling我在前面有'返回'。沒有'return'的代碼是我正在調試的代碼。增加了'return'和相同的值。好看的 – Liondancer

+0

'.then'回調中的類似:你必須做'return fetch(...)',否則承諾沒有正確鏈接。 –

回答

1

只是改變這一行

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

這個

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

所以promise.all將解決畢竟嵌套的承諾已經解決,以便有效載荷填滿。