无法使用回调获取结果 [英] Unable to fetch results using callback

查看:56
本文介绍了无法使用回调获取结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 node 节点中使用两个不同的函数 getPosts() getContent()在其中提供回调,以打印调用独立函数 getResult()的结果。

I've written a script in node using two different functions getPosts() and getContent() supplying callback within them in order to print the result calling a standalone function getResult(). The selectors defined within my script is flawless.

但是,当我执行脚本时,它不会打印任何内容。它也不会引发任何错误。我尝试模仿 Neil 所提供的逻辑-print-the-content-of-other-function / 55594953?noredirect = 1#comment97887210_55594953>此信息。

However, when I execute my script, It prints nothing. It doesn't throw any error either. I tried to mimic the logic provied by Neil in this post.

我该怎么做?

How can I make it a go?

我到目前为止已经写过:

I've written so far:

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

const url = 'https://stackoverflow.com/questions/tagged/web-scraping';

function getPosts(callback){
  request(url, function (error,response, html) {
    if (!error && response.statusCode == 200){
      var $ = cheerio.load(html);
      $('.summary .question-hyperlink').each(function(){
        var items = $(this).text();
        var links = $(this).attr("href");
        callback(items,links);
      });
    }
  });
}

function getContent(item,link,callback){
  request(link, function (error,response, html) {
    if (!error && response.statusCode == 200){
      var $ = cheerio.load(html);
      var proLink = $('.user-details > a').eq(0).attr("href");
      callback({item,link,proLink});
    }
  });
}

function getResult() {
  getPosts(function(item,link) {
    getContent(item,link,function(output){
      console.log(output);
    });
  });
}

getResult();


推荐答案

链接 getPosts 接收到的c $ c>值是相对链接,表示请求失败。您可以在其自己的变量中提取主机名,然后从主机名+相对链接中创建完整的URL。

The link value that you receive from getPosts is a relative link which means that the request fails. You can extract the hostname inside its own variable and create the full URL from the hostname + the relative link.

const host = 'https://stackoverflow.com';
const url = '/questions/tagged/web-scraping';

// ...

function getContent(item,link,callback){
  // Here we use the absolute URL
  request(host + link, function (error,response, html) {
    if (!error && response.statusCode == 200){
      var $ = cheerio.load(html);
      var proLink = $('.user-details > a').eq(0).attr("href");
      callback({item,link,proLink});
    }
  });
}

这篇关于无法使用回调获取结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆