NodeJS 尝试获取foreach [副本]之外的promise

z4iuyo4d  于 2023-02-08  发布在  Node.js
关注(0)|答案(1)|浏览(129)
    • 此问题在此处已有答案**:

(33个答案)
How do I return the response from an asynchronous call?(41个答案)
2天前关闭。
我正在使用node.js中的puppetter从一个站点获取数据,我正在获取数据,但我想我在promisse上遇到了一个小问题。
我会得到这个数据,并分裂成两个"变量"(国家和联赛),但首先需要从网站上获得的数据。
发生的事情是,当我console.log里面的"foreach"它显示我需要的数据,但它出来,它console.log一个未定义的值。我搜索,看到它是因为它是一个promisse,但我不能做它propely。
我在代码中注解了我正在尝试做的事情。

try {
            //using library puppeteer to get data from flashscore.com.br or the site you want

            //you need to put the headless option as false to see the browser opening
            const browser = await puppeteer.launch({ headless: false });
            const page = await browser.newPage();
            await page.goto("http://m.flashscore.com.br");

            //getting the element that contains the games
            const element = await page.$("div.soccer > div#score-data");


            const dataCountryAndLeague = await element?.$$(`h4`,);

            var data: string | null 
            dataCountryAndLeague?.forEach(element => {
                element.getProperty('textContent').then(textContent => textContent.jsonValue().then(async (cld) => {
                    console.log(cld); //getting the country and league (THE Data its showed as ia want)
                    data = cld; //trying to pass the data to a variable
                    
                })
                );
                console.log(data); //trying to print the data outside the forEach, but its undefined
            });


        } catch (error) {
            console.log(error + "Erro identificado ao tentar acessar os dados da página");
            return error + "Erro identificado ao tentar acessar os dados da página";
        }

我期待着做我之前解释的事情。
谢谢您的关注。

mzsu5hc0

mzsu5hc01#

我们得等所有的承诺都兑现了。比如:

async function handle(element) {
  const textContent = await element.getProperty('textContent');
  return textContent.jsonValue();
}

const promises = dataCountryAndLeague?.map(element => handle(element)) ?? [];

const data = await Promise.all(promises);
console.log(data) // All your data goes here

相关问题