亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何訪問在另一個函數中異步創建的全局數據數組?

如何訪問在另一個函數中異步創建的全局數據數組?

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條經驗 獲得超3個贊

不要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 關注
  • 164 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號