Simon Breton Simon Breton - 2 months ago 10
Javascript Question

Chaining function as promise

I'm building a little node js data scrapping function inside a bigger app. I'm not so confortable with Javascript promises so please forgive my misunderstanding. Not sure that my title really frame my issue.

so I have this :

const getAxiosUrls = function() { axios.get("http://localhost:3000/gatable")
.then(function (response) {
return urls = response.data.rows.map( ([x, y, z]) => y )
})}


and this :

const getNbShares = function() {
Promise.map(urls, requestPromise)
.map((htmlOnePage, index) => {
const $ = cheerio.load(htmlOnePage);
const share = $('.nb-shares').html();
let shareTuple = {};
shareTuple[urls[index]] = share;
return shareTuple;
})
.catch((e) => console.log('We encountered an error' + e));
}


and I would like to do this :

getAxiosUrls()
.then(getNbShares)
.then(res.json)


I've tried some stuff but most of the time I've got the following error :
Cannot read property 'then' of undefined
. Also to be sure that my
getAxiosUrls
works correctly, I've done this

getAxiosUrls()
setTimeout(function() {console.log(urls)},5000)


and the log return me the response as expected. So what did I miss ?

Answer

The functions getAxiosUrls and getNbShares don't return the promise. It should be

const getAxiosUrls = function() { 
    return axios.get("http://localhost:3000/gatable")
      .then(function (response) {
          return urls = response.data.rows.map( ([x, y, z]) => y )
    })
}

and

const getNbShares = function(urls) {
    return Promise.map(urls, requestPromise)
        .map((htmlOnePage, index) => {
            const $ = cheerio.load(htmlOnePage);
            const share = $('.nb-shares').html();
                let shareTuple = {};
                shareTuple[urls[index]] = share;
                return shareTuple;
        })
        .catch((e) => console.log('We encountered an error' + e));
}

As a side note: I would recommend removing the .catch in the getNbShares function, since this will cause the promise returned in this function to resolve to undefined in case of an error (you're not returning anything in the catch handler). It is often better to add error handling at the very end of your promise chain, unless there is something you can do to recover from the error.