Friday 9 June 2017

Loop over a Promise https/http Request

I'm trying to hit an endpoint that returns a list of values. I only want to resolve the data returned from the endpoint if the number of items in the list returned from the API is >= 50.

So I'm increasing the date range of the data by 1 every iteration of the while loop. This seems to work fine (the logged variables and URL are correct). However it seems the API call is never made. What am I missing?

return new Promise(function(resolve, reject){

        while(postCount <=50) {

            console.log('Making requests');

            let startDate = moment().tz("Asia/Seoul").subtract(startDateCounter, "days").format("YYYY-MM-DD");

            console.log('Start Date: ', startDate);
            console.log('End Date: ', endDate);

            let apiURL = 'https://acme.com/api/' + id + '&' +
                'start=' + startDate + '&end=' + endDate;

            https.get(apiURL, function (response) {

                let data = '';

                response.on('data', function (body) {
                    data += body.toString();
                });

                response.on('end', function () {

                    console.log('Hello')

                    data = JSON.parse(data);

                    let statusList = [];

                    postCount = data['posts'].length;

                    console.log('Found',postCount,'posts.');

                    if(data['posts'].length >= 50) {
                        for (var post in data['posts']) {
                            var index = data['posts'][post].url.lastIndexOf('/');
                            statusList.push(data['posts'][post].url.substr(index + 1));
                        }

                        resolve(statusList);

                    }

                });

            });

            startDateCounter++

        }

    });



via Tyler Mills

No comments:

Post a Comment