Return results from Request.js request method?

2019-02-24 16:10发布

问题:

var request = require('request');
var cheerio = require('cheerio');


    request(url, function (error, response, html) {
        if (!error && response.statusCode == 200) {
            var $ = cheerio.load(html);


            var link = $('.barbar li a');
            var Url = link.attr('href');
            var Title = link.find('span').first().text();
            var results = [Url, Title];


            return results;
        } 
    });

console.log(results);

results is undefined...

I want to use the results to add a hyperlink to an HTML page, but I don't know how to access the results/ return them outside of the callback. I've seen other posts but they all use other libraries and usually only have an example using console.log within the scope.

回答1:

var request = require('request');
var cheerio = require('cheerio');

function doYourThing(callback){
  request(url, function (error, response, html) {
    if(error){ return callback(error) };
    if (!error && response.statusCode == 200) {
      var $ = cheerio.load(html);
      var link = $('.barbar li a');
      var Url = link.attr('href');
      var Title = link.find('span').first().text();
      var results = [Url, Title];
      callback(null, results);
    } 
  });

function main(){
  doYourThing(function(err, results){
    console.log(err, results);
  });
};

main();