在console.log工作时,返回未定义。为什么

时间:2019-08-05 07:33:24

标签: javascript node.js request cheerio

想返回对象数组,但返回时显示“未定义”。但是在console.log上工作正常。

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

const getData = () => {
  request('https://news.google.com/topics/CAAqJggKIiBDQkFTRWdvSUwyMHZNRFp0Y1RjU0FtVnVHZ0pKVGlnQVAB?hl=en-IN&gl=IN&ceid=IN%3Aen',(err,response,html)=>{
    if(!err && response.statusCode == 200){
      const $ = cheerio.load(html);
      const news = $('.NiLAwe');
      const list = [];
      news.each((i,el)=>{
        const newsLink = $(el).find('.ipQwMb').html();
        const newsImg = $(el).find('.tvs3Id').attr('src');
        while(list.length <= 20){
          list.push({
            link:newsLink,
            img:newsImg
          })
        }
      });
      return list //Shows Undefined
    }
  });
}
console.log(getData())

0 个答案:

没有答案