为了账号安全,请及时绑定邮箱和手机立即绑定

如何访问在另一个函数中异步创建的全局数据数组?

如何访问在另一个函数中异步创建的全局数据数组?

MMMHUHU 2023-11-11 21:06:01
正如标题所示,我只想访问在 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();
查看完整描述

1 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超2个赞

不要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

})();


查看完整回答
反对 回复 2023-11-11
  • 1 回答
  • 0 关注
  • 71 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信