2017-03-09 56 views
0

以下代碼使用GitHub API檢索版本上的數據。不幸的是,這隻會返回30(默認)或最多100個項目。如何迭代請求調用並將結果存儲在對象上?

request(`https://api.github.com/repos/${owner}/${repo}/releases?page=1&per_page=30`, options, function (error, response, body) { 
    if (response.statusCode !== 200) { 
     return console.log(`Error: response code ${response.statusCode}`) 
    } 

    let data = JSON.parse(body); 

    data.forEach(function(element) { 
     // do things with data 
    }); 
}); 

使用page參數,應該可以檢索超過每頁最大值的項目。問題是:如何迭代這些調用並返回一個包含所有結果的對象?

這是我曾嘗試:

function getReleases(callback, page = 1) { 
    request(`https://api.github.com/repos/${program.owner}/${program.repo}/releases?page=${page}&per_page=30`, options, function (error, response, body) { 
     if (response.statusCode !== 200 || error) { 
      console.log(`Error ${response.statusCode}`); 
      callback(null) // not sure about this 
     } 

     let data = JSON.parse(body); 
     callback(data); 
    }); 
} 

function formatReleaseData(data) { 
    // do things with data 
} 

formatReleaseData(show_page_count); 
+0

有沒有我可以看到的回調示例? – Raymond

+0

@Raymond請看看我的編輯 – idleberg

回答

1

這裏是如何使用ES6發電機來模擬同步請求,並更好地控制流量做到這一點。 你可以閱讀這article更深的概念。

我使用bluebird promisify和管理生成器。

查看下面的代碼。

const request = require('request'); 
const Promise = require('bluebird'); 


function promisifyRequest(currentPage) { 
    const url = `https://api.github.com/repos/${owner}/${repo}/releases?page=${currentPage}&per_page=30`; 

    return new Promise((resolve, reject) => { 
    request(url, options, (err, res, content) => { 
     if (res.statusCode !== 200) { 
     return reject(res.statusCode); 
     } 
     resolve(JSON.parse(content)); 
    }); 
    }); 
} 

function * doRequest() { 
    const result = []; 
    let currentPage = 1; 
    //Might run until gets a empty array. 
    while (true) { 
    let data = yield promisifyRequest(currentPage); 
    if (!data.length) break; 
    //Appends the results of the current page to the total result. 
    result.splice(result.length, 0, ...data); 
    currentPage = currentPage + 1; 
    } 

    return result; 
} 


Promise.coroutine(doRequest)() 
    .then(result => { 
    //Do something with the result 
    }) 
    .catch(errCode => console.log(`Error: response code ${errCode}`)); 
相關問題