如何解决如何在异步函数之外返回我用 ppeteer 刮取的值
我正在使用电报编写电报机器人,一整天都遇到问题。我试图做的是让我的电报机器人接收分开的持有量和价值来打印每个令牌的价值,但我不知道如何将价值返回给机器人。如果我将机器人留在功能之外,当我尝试像这样运行它时,它也会抛出异常。出于隐私原因,我关闭了链接,但数字无关紧要,因为它们可以正确划分。
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(`,``));
let tokenCurrentPrice = holdingPrice / amount;
return tokenCurrentPrice;
});
console.log(tokenPrice);
})();
//bot.command('price',(ctx) => ctx.reply(tokenPrice))
解决方法
如果我将机器人留在函数之外,当我尝试像这样运行它时,它会抛出异常。
const bot
在不同的范围内声明。常量是块作用域的,所以名称 bot
没有在作用域之外定义。
为了说明问题:
{
const a = 5
}
console.log(a);
这将返回 ReferenceError
,因为 a
位于不同的作用域中。
但这很好:
{
const a = 5
console.log(a);
}
我不知道如何将值返回给机器人。
你的 IIHF 是一个异步函数,所有的异步函数都返回一个承诺。为了说明这一点,这不会打印 5,因为 Promise 尚未解决:
async function getValue () {
return 5;
}
console.log(getValue());
如果要获取值,需要等待promise得到解决:
async function getValue () {
return 5;
}
(async () => {
console.log(await getValue());
})();
还要确保您没有在异步范围之外使用 await
:
async function getValue () {
return 5;
}
console.log(await getValue());
这行不通,而且会报错。这就是我使用具有异步作用域的 IIHF 的原因。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。