Return results from Request.js request method?

安稳与你 提交于 2019-12-01 20:39:57

问题


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


来源:https://stackoverflow.com/questions/20081157/return-results-from-request-js-request-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!