0

I am trying to return page data which I get from a public API using a Google Cloud function. The api returns a paged result so I wrote a recursive function that concatenates the data of every page and then when all pages have been added return the data. For some reason my main function that calls the recursive function responds before the allData variable which depends on the recursive function's final value is resolved. When I debug I can see that when my main function responds the allData variable is still undefined. Any idea how I can make this work and only respond when that variable has a value?

my code:

const http = require('http');
const request = require('request-promise');

exports.getPages = (req, res) => {        
        let allData = getPageData(1);



        console.log(allData);
        res.send({"allData":allData});           



};



function getPageData(page, data) {
    request({
        "method": 'GET',
        "uri": `https://testing-api-v3.hellopeter.com/businesses/top?page=${page}`,
        "json": true,
        "resolveWithFullResponse": true
    }).then((res) =>  {                
        if (!data) {
            data = [];            
        }
        data.push(res.body.data);
        if (res.body.meta.last_page > page) {
            return getPageData(page + 1, data);
        } else if (page === +res.body.meta.last_page){
            return data;
        }        
    })
    .catch((e) => {
        console.log(err);
    });
}
user2094257
  • 1,645
  • 4
  • 26
  • 53
  • 1
    The call to `request` loads data asynchronously. This means you can't return it from `getPageData` and instead should return a promise (such a `request` itself does) or pass in a callback. For more on this see https://stackoverflow.com/questions/37771386/how-to-wait-a-request-response-and-return-the-value and https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Frank van Puffelen Mar 04 '18 at 15:21
  • @Frank van Puffelen Thanks I realized this just now... Do you know of any way to wait for the recursive function to return before continuing execution? – user2094257 Mar 04 '18 at 15:22

0 Answers0