Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why Axios don't wanna working in function? [Edited]

[Edited] I wanna create node js scraper. Thanks for Shubham Khatri helping! But i get new suggestion, i trying get ‘value’ from ‘.then’ and it send me ‘value is not defined’. Please says me how to fix this? I trying and don’t find how to fix this!

const cheerio = require('cheerio')
const url = 'XXX'
GetInfo = function() {
  return axios.get(url)
    .then(response => {
        const Response = response.data
        const $ = cheerio.load(Response)
        const text = $('span.bookbuy').text()
        return text;
    })
}
GetInfo().then((value) => console.log("Price today is:" + value));
const BuyPrice = value

I try add to my scraper return, and says undefined, and i don’t know what to need to add, to make it work. I created scraper to get info of price book, if there is a discount, i go to buy this book.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

axios call is async and it returns a promise which is resolved when the call has returned a response or an error.

Since the console log is executed before the promise has resolved, you don’t see the result you expect.

To log the returned value you need to use the .then function on the returned promise

const axios = require('axios')

const cheerio = require('cheerio')
const url = 'XXX'
GetInfo = function() {
  return axios.get(url)
    .then(response => {
        const Response = response.data
        const $ = cheerio.load(Response)
        const text = $('span.bookbuy').text()
        return text;
    })
}
GetInfo().then((value) => console.log(value));

Read more about Promises and async calls here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading