alsotang / node-lessons

:closed_book:《Node.js 包教不包会》 by alsotang
16.53k stars 4.7k forks source link

Hi,alsotang,请教一个问题,谢谢 #161

Open BM0124 opened 5 years ago

BM0124 commented 5 years ago

我在做《Node.js 包教不包会》系列里面 lesson4的挑战题,取“积分”的时候,遇到一个难点,不知道怎样用superagent里面取到的变量取修改外面的全局变量,代码(部分)如下:

var topicUrl = topicPair[0];
var topicHtml = topicPair[1];
var $ = cheerio.load(topicHtml);
//取评论人的积分
 var authorUrl = url.resolve(cnodeUrl,$('.dark.reply_author').eq(0).attr('href'));
 let score1 =0;
 superagent.get(authorUrl)
 .end(function (err, sres) {
    // 常规的错误处理
    if (err) {
    return next(err);
    }
  const $2 = cheerio.load(sres.text);
  score1 = $2('.unstyled .big').eq(0).text().trim();
  console.log("In ,score1:"+score1);          
})
return ({
  title: $('.topic_full_title').text().trim(),
  href: topicUrl,
  comment1: $('.reply_content').eq(0).text().trim(),
  author1: $('.dark.reply_author').eq(0).text().trim(),
  score1: score1
});
superagent里面的score1已经取到积分了,但没办法传出来。。。谢谢
alsotang commented 5 years ago

你这个return是没法传递score1出来的,你要把你的return改成一个callback来传值给上层。

BM0124 commented 5 years ago

你这个return是没法传递score1出来的,你要把你的return改成一个callback来传值给上层。

感谢大神回复,不过我上面没表达清楚意思哈,我不是想把最后return ({..})里面的score1传出来,而是想让superagent里面的score1 = $2('.unstyled .big').eq(0).text().trim();去修改superagent外面初始化的那个let score1=0, 让其不为0,而是等于从页面抓到的值,比如10,如果这样的话,最后return({})语句里面的那个score1也就为10了,而不是等于初始化的0,非常感谢!~

alsotang commented 5 years ago

你去了解一下 callback逻辑的执行顺序。用console.log看看是return先执行还是callback里面的语句先执行

BeiMing notifications@github.com 于2018年10月8日周一 下午9:22写道:

你这个return是没法传递score1出来的,你要把你的return改成一个callback来传值给上层。

感谢大神回复,不过我上面没表达清楚意思哈,我不是想把最后return ({..})里面的score1传出来,而是想让superagent里面的score1 = $2('.unstyled .big').eq(0).text().trim();去修改superagent外面初始化的那个let score1=0, 让其不为0,而是等于从页面抓到的值,比如10,如果这样的话,最后return({})语句里面的那个score1也就为10了,而不是等于初始化的0,非常感谢!~

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/alsotang/node-lessons/issues/161#issuecomment-427830509, or mute the thread https://github.com/notifications/unsubscribe-auth/ABGB7w7RoSqxUQYLn5oZ_3lkjoBvadpMks5ui1GTgaJpZM4XL6TT .

-- GitHub: https://github.com/alsotang