0

I have a getValidUrls function that takes a maxId param.

Within this function it loops backwards and sends a request for the url.

Each loop decrements the maxId.

My issue is that I am trying to add these valid urls to an array, but I cannot update the array from within the .then of the promise. I have added a simple total variable to see if I could increment it and could not.

getValidUrls = (maxId) => {
    return new Promise((resolve, reject) => {
        let validUrls = [];
        let idCounter = maxId;
        let total = 0; // test to see if updated from inside (it doesn't)

           // while(validUrls.length < 10 && idCounter > 0) {
            for(let i = maxId; i > 0; i--){

                let newsUrl = `https://hacker-news.firebaseio.com/v0/item/${i}.json?print=pretty`;
                //console.log(newsUrl); // this shows all the urls & works

                getJSONObject(newsUrl)
                .then((story) => {
                    total++;
                    console.log(total); // this never gets shown
                    return getUserObject(story.by);
                }).then((user) => {
                    if(user.karma > 5) {
                        validUrls.push(story);
                        if(validUrls.length >= 10) {
                            resolve(validUrls);
                        }
                    } 
                });
            }
    });
};

The following returns a json object for the url

getJSONObject = (url) => {
    return new Promise((resolve, reject) => {
        console.log(url); // this works and shows all urls
        https.get(url, (response) => {
            response.on('data', (data) => {
                console.log(JSON.parse(data)); // This never gets shown
                resolve(JSON.parse(data));
            }, (err) => reject(err));
        }, (err) => reject(err));
    });
};
Mike
  • 15
  • 4
  • The the `getJSONObject` function called at all? – Jonathan Newton Feb 02 '17 at 14:44
  • Hi, what library is used with the variable 'https' ? Set a log before 'response.on' to see if your 'https.get' works. You should log the error callback too. – PortePoisse Feb 02 '17 at 14:45
  • add console.log after this line : https.get(url, (response) => { – challenger Feb 02 '17 at 14:50
  • I am getting nothing with the console.log after the https.get. But the url is valid and works if typed into browser – Mike Feb 02 '17 at 15:13
  • Try using `Promise.all` to aggregate the promises, and resolving each of them with a 1 if successful, 0 if not (or, truthy/falsy). Then do a `reduce` on the array to get the number of successes. – Seiyria Feb 02 '17 at 16:59
  • Avoid the [promise constructor anti-pattern](http://stackoverflow.com/q/23803743/1048572). – jib Feb 05 '17 at 19:16

0 Answers0