-1

I'm trying to return an array from request but its returning null

request("https://***some url*****/", function (err, resp, body) {
        var links_ = [];

        if (!err && resp.statusCode === 200) {
            var $ = cheerio.load(body);
            $('.div-topics-index > ul > li').map(function (i, links) {
                links_.push($(links).children('a').attr('href').toString());
            });
            return links_;
        }
    });

I tried this also Return value from Request but doesn't worked. So how do I return values from the request in NodeJS?

Ajay Kumar
  • 115
  • 5
  • 10
  • Did you try printing ```$(links).children('a').attr('href').toString()``` to console? – Yogeshwar Singh Dec 29 '19 at 12:15
  • Yes it's printing values to the console – Ajay Kumar Dec 29 '19 at 12:26
  • `request()` is asynchronous. Your return value is only from your callback (which does nothing useful), not from the containing function. See the question yours was marked a duplicate of. You will need to use a callback or a promise to communicate back the return value from an asynchronous call. – jfriend00 Dec 29 '19 at 17:59

2 Answers2

1

It's better to use promise version of request package. It is request-promise. The code will look like this and much more simple.

const cheerio = require('cheerio');
const rp = require("request-promise");

const options = {
    uri: 'http://www.someurl.com',
    transform: function (body) {
        return cheerio.load(body);
    }
};

rp(options)
    .then(function ($) {
        // Process html like you would with jQuery...
    })
    .catch(function (err) {
        // Crawling failed
    });

Hope this helps

Ashish Modi
  • 7,529
  • 2
  • 20
  • 35
0

You are returning from callback function. It doesn't make sense. Return statements from callbacks are ignored.

Yogeshwar Singh
  • 1,245
  • 1
  • 10
  • 22