简体   繁体   中英

Return results from Request.js request method?

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM