我如何 return 我在异步函数之外用 puppeteer 抓取的值

How do I return the value I scraped with pupeteer outside of my async function

我正在使用电报编写一个电报机器人,而且我 运行整天都在处理问题。我想做的是让我的电报机器人接收除以持有量和价值来打印每个令牌的价值,但我不知道如何 return 机器人的价值。如果我将机器人留在功能之外,当我尝试 运行 时它也会抛出异常。出于隐私原因,我关闭了链接,但数字无关紧要,因为它们可以正确划分。

const { Telegraf } = require('telegraf')
const puppeteer = require("puppeteer-extra")
const stealth = require("puppeteer-extra-plugin-stealth")()
const anon = require(`puppeteer-extra-plugin-anonymize-ua`)()
puppeteer.use(stealth).use(anon);

(async () => {

  const bot = new Telegraf('my telegraf bot ID, can't post it')

    //the token URL
  let tokenUrl = 'https://bscscan.com/tokenholdings?a=0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c';

  let browser = await puppeteer.launch();
  let page = await browser.newPage();

  await page.goto(tokenUrl, { waitUntil: 'networkidle2' });

  let tokenPrice = await page.evaluate(() => {

    let amount = document.querySelector('div[class="table-responsive mb-2 mb-md-0"]>table>tbody> tr:nth-child(4) > td:nth-child(4)').innerText;
    //console.log(amount);
    amount = Number(amount.replace(`,`, ``));

    let holdingPrice = document.querySelector('span[class="h5 mr-1 mb-0"]').innerText;
    //console.log(holdingPrice);
    holdingPrice = Number(holdingPrice.replace(`$`, ``).replace(`,`, ``).replace(`,`, ``).replace(`,`, ``));

    let tokenCurrentPrice = holdingPrice / amount;

    return tokenCurrentPrice;

  });

  console.log(tokenPrice);

})();

//bot.command('price', (ctx) => ctx.reply(tokenPrice))      

It throws an exception when I try to run it like this if I leave the bot outside of function.

const bot 在不同的范围内声明。常量是块范围的,因此名称 bot 未在范围外定义。

说明问题:

{
    const a = 5
}

console.log(a);

这 returns ReferenceError 因为 a 生活在不同的范围内。

但这很好:

{
    const a = 5
    console.log(a);
}

I cannot figure out how to return the value to bot.

你的 IIHF 是一个异步函数,所有异步函数 return 一个承诺。为了说明这一点,这不会打印 5 因为承诺尚未解决:

async function getValue () {
    return 5;
}

console.log(getValue());

如果要获取值,需要等待promise得到resolved:

async function getValue () {
    return 5;
}

(async () => {
    console.log(await getValue());
})();

还要确保您不在异步范围之外使用 await

async function getValue () {
    return 5;
}

console.log(await getValue());

这行不通,而且会报错。这就是为什么我使用带异步范围的 IIHF。