【问题标题】:Trying to return array of objects from async function, array returned undefined试图从异步函数返回对象数组,数组返回未定义
【发布时间】:2021-05-20 09:17:34
【问题描述】:

我一直在研究刮板功能。

现在关于应用程序:有两个刮板,从两个页面中刮取有关公寓的数据。现在,当数据完成抓取后,它被传递给mergeData 函数,该函数的目标是将所有从scrapers 传递的对象数组合并到一个包含来自scrapers 的所有对象的数组中,然后传递给insert 函数,被插入到数据库中。

现在这里是刮板之一

const data_functions = require('../data-functions/data-functions');
const axios = require('axios'); //npm package - promise based http client
const cheerio = require('cheerio'); //npm package - used for web-scraping in server-side implementations

//santScaper function which as paramater needs count which is sent in the scraping-service file.
exports.santScraper = async (count) => {
  const url = `https://www.sant.ba/pretraga/prodaja-1/tip-2/cijena_min-20000/stranica-${count}`;

  const santScrapedData = [];
  try {
    load_url(url, santScrapedData);
  } catch (error) {
    console.log(error);
  }
};

//Function that does loading URL part of the scraper, and starting of process for fetching raw data.
const load_url = async (url, santScrapedData) => {
  await axios.get(url).then((response) => {
    const $ = cheerio.load(response.data);
    fetch_raw_html($).each((index, element) => {
      process_single_article($, index, element, santScrapedData);
    });

    data_functions.mergeData(santScrapedData); <- here is data passed into the mergeData component
  });
};

//Part where raw html data is fetched but in div that we want.
const fetch_raw_html = ($) => {
  return $('div[class="col-xxs-12 col-xss-6 col-xs-6 col-sm-6 col-lg-4"]');
};

//Here is all logic for getting data that we want, from the raw html.
const process_single_article = ($, index, element, santScrapedData) => {
  const getLink = $(element).find('a[class="re-image"]').attr('href');
  const getDescription = $(element).find('a[class="title"]').text();
  const getPrice = $(element)
    .find('div[class="prices"] > h3[class="price"]')
    .text()
    .replace(/\.| ?KM$/g, '')
    .replace(',', '.');
  const getPicture = $(element).find('img').attr('data-original');
  const getSquaremeters = $(element)
    .find('span[class="infoCount"]')
    .first()
    .text()
    .replace(',', '.')
    .split('m')[0];
  const pricepersquaremeter =
    parseFloat(getPrice) / parseFloat(getSquaremeters);

  santScrapedData[index] = {
    id: getLink.substring(42, 46),
    link: getLink,
    description: getDescription,
    price: Math.round(getPrice),
    picture: getPicture,
    squaremeters: Math.round(getSquaremeters),
    pricepersquaremeter: Math.round(pricepersquaremeter),
  };
};

现在是mergeData 组件

let mergedApartments = [];
exports.mergeData = async (apartments) => {
  //Fetching all apartments that are passed from scraper(s)
  mergedApartments = mergedApartments.concat(apartments);
  //Sending data for validation to the validation function
  return mergedApartments;
};
this.mergeData().then((result) => console.log(result));

现在返回 [undefined],我希望在其中填充来自两个刮板的对象。

现在我想要的是:第一个刮板返回数组中约 9 个对象,而第二个刮板返回数组中约 30 个对象。现在我希望将这两个进入函数的数组合并并作为一个带有对象的数组传递(所以mergedApartments.length 将是〜39。我无法实现这一点,我已经尝试了其他问题的许多解决方案,但没有成功。

什么是正确的解决方案?谢谢!

【问题讨论】:

  • this.mergeData().then((result) =&gt; console.log(result)); - 在您的 srcap 函数之前调用此字符串(当您需要此模块时)。在这里,您将 undefined 值(空函数参数)添加到您的累积数组并将此数组发布到控制台。难怪你看到[undefined]。尝试在废弃功能完成后发布控制台日志
  • 谢谢,很有道理!那么,函数究竟如何知道刮板是否完成了他们的工作?
  • 这有很多选择,例如你可以使用原生js Promise.all,或者计算你的回调调用,或者使用native node events functional,或者使用特殊的包比如async,bluebird或deferred等
  • 非常感谢。我将探索bluebird。另外,如果你能举出一些已经做过类似我的例子的例子,或者你将如何处理这个问题,我将非常感激。

标签: javascript node.js arrays object


【解决方案1】:

// Your data module:
const data_functions = {
  mergedApartments: [],
  mergeData(apartments){ this.mergedApartments.push(...apartments) },
};

// Scrape mock: async function, returning array of data
const load_url = () => new Promise(resolve => setTimeout(() => resolve([1,2,3,4]), 2000));

// scraper 1:
const santScraper = async () => {
  const data = await load_url(); // Imagine here all operations for scraping data till you have array..
  data_functions.mergeData(data);
  return data;
};

// scraper 2:
const anotherScraper = async () => {
  const data = await load_url(); // Imagine here all operations for scraping data till you have array..
  data_functions.mergeData(data);
  return data;
};


// Call both scrapers, await them and get all in one array:
Promise.all([santScraper(), anotherScraper()])
  .then(() => console.log(data_functions.mergedApartments))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 2018-09-22
    • 2016-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多