【问题标题】:How to access global data array created asynchronously in another function?如何访问在另一个函数中异步创建的全局数据数组?
【发布时间】:2021-03-22 10:43:43
【问题描述】:

正如标题所说,我只想访问我在 getSubURLs() 函数中填充到 getURLs() 中的全局数组数据,以便我可以操作其中的数据。有人可以让我知道我该怎么做吗?提前非常感谢您!

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

let URL = 'https://toscrape.com';
const urlQueue = [];

const getURLS = async () => {
  await axios
    .get(URL)
    .then((res) => {
      const data = res.data;
      const $ = cheerio.load(data);

      $("a[href^='http']").each((i, elem) => {
        const link = $(elem).attr('href');
        if (urlQueue.indexOf(link) === -1) {
          urlQueue.push(link);
        }
      });
      console.log(urlQueue);
      return urlQueue;
    })
    .catch((err) => {
      console.log(`Error fetching and parsing data: `, err);
    });
};

const getSubURLs = async () => {
  // call urlqueue array here after it finishes being created 
}

getURLS();

【问题讨论】:

  • 当你真的需要异步函数来互相等待时,为什么还要使用它们?
  • 老实说,我是个菜鸟,我不知道如何对这些数据进行排队并使用它,以便再次抓取。你建议我做什么?
  • 我不知道,我错过了很多关于你想要做什么的信息,但根据你的例子,你似乎不需要异步
  • 我正在尝试抓取一个网站,然后将来自该网站的所有 url 排队,然后关注它们。在 get suburls() 中,我将获取该数组并遍历它们,拉取它们的每个 url。

标签: javascript node.js arrays asynchronous


【解决方案1】:

不要将async.then 语法混用,只使用await 结果:

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

let URL = 'https://toscrape.com';
const urlQueue = [];

const getURLS = async () => {
    try {
        const res = await axios.get(URL);
        const data = res.data;
        const $ = cheerio.load(data);

        $("a[href^='http']").each((i, elem) => {
            const link = $(elem).attr('href');
            if (urlQueue.indexOf(link) === -1) {
                urlQueue.push(link);
            }
        });
        console.log(urlQueue);
    } catch (err) {
        console.log(`Error fetching and parsing data: `, err);
    }
};

// in case there's no top-level await
(async () => {
    await getURLS();

    // do something about urlQueue
})();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 2013-01-24
    相关资源
    最近更新 更多