【问题标题】:How to get the function returns with async/await methods如何使用 async/await 方法获取函数返回
【发布时间】:2019-09-13 05:39:20
【问题描述】:

我正在使用cheerio 从确实(至少 50 个招聘信息)中抓取招聘信息。

我已经使用cheerio 获得了抓取的数据。但我不知道如何使用 async/await 方法将这些数据存储在对象中

工具:node.js、cheerio、request。

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

const fetchIndeedData = async () => {
    let start = 0;
    let title = [];
    let company = [];
    let location = [];
    let summary = [];

    for (let i = 0; i < 5; i++) {
        let url = `https://ca.indeed.com/jobs?q=full+stack+developer&l=Toronto,+ON&start=${start}`;
        await request(url, (err, response, body) => {
            const $ = cheerio.load(body);

            $('#resultsCol .jobsearch-SerpJobCard .title a').each((i, item) => {
                title.push(item.attribs.title);
            });

            $('#resultsCol .jobsearch-SerpJobCard .company a').each((i, item) => {
                company.push($(item).text().trim());
            });

            $('#resultsCol .jobsearch-SerpJobCard .location').each((i, item) => {
                location.push($(item).text());
            });

            $('#resultsCol .jobsearch-SerpJobCard .summary ').each((i, item) => {
                summary.push($(item).text());
            });

        });
        start += 10;
    }

    const jobPostings = {
        title,
        location,
        company,
        summary
    };

    return jobPostings;
};

const getData = fetchIndeedData().then(data => console.log(data));

当我调用 getData 函数时,我无法获取任何数据。 当我在返回之前运行 console.log(jobPostings) 时。我仍然无法获取数据...... 有人知道吗?

【问题讨论】:

  • getData 不是函数,而是承诺。
  • 您的console.log(data) 是您访问数据的地方。那就是你使用它的地方。 getData 只是承诺。

标签: node.js async-await cheerio


【解决方案1】:

这是我认为使用 async / await (you will need request-promise or similar) 时的样子:

const fetchIndeedData = async () => {
  let urls = [0,1,2,3,4].map(start => `https://ca.indeed.com/jobs?q=full+stack+developer&l=Toronto,+ON&start=${start}`)
  let responses = await Promise.all(urls.map(url => request.get(url)))
  let $$ = responses.map(response => cheerio.load(response))
  return $$.map($ => {
    return {
      title: $('title').text(),
      // more cheerio code here
    }
  })
}

;(async function(){
  const data = await fetchIndeedData()
  console.log(data)
})()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-06
    • 2019-03-01
    • 2020-03-12
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 2014-11-01
    相关资源
    最近更新 更多