gpt4 book ai didi

javascript - 为什么函数getPrice()仅调用一次?

转载 作者:行者123 更新时间:2023-12-03 13:23:39 26 4
gpt4 key购买 nike

为什么函数getPrice()在我的代码中仅被调用过一次?我认为每次 telegrambot 收到消息时,都必须调用它。还是我错了?

const Nightmare = require('nightmare')
const nightmare = Nightmare({show: true})

const TelegramBot = require('node-telegram-bot-api')
const TOKEN = ''

const bot = new TelegramBot(TOKEN, {polling: true})
console.log('Bot has been started...')

let price

function getPrice(){
nightmare
.goto('https://uk.investing.com/commodities/real-time-futures')
.evaluate(()=>{
let gold = document.querySelector('.pid-68-last').innerText
let goldAug20 = document.querySelector('.pid-8830-last').innerText
let diff = Math.abs( gold.replace(',','') - goldAug20.replace(',',''))
return diff.toFixed(2)
})
.end()
.then(data =>{
price = data
//console.log(price)
return nightmare
})

}

bot.on('message', (msg) => {
getPrice()
bot.sendMessage(msg.chat.id, price)
})

最佳答案

正确的做法是,每次getPrice()事件触发时都应调用message,因此该事件可能仅触发一次。也许添加控制台日志以验证事件是否在每条消息上触发。
但是,您的代码还有另一个问题,那就是price变量将在事件发生后设置,因为它是异步的。我对Nightmare库不熟悉,但是根据您的代码,您似乎可以对async/await进行一些简单的更改以使其正常工作:

 // Add the 'async' keyword to make this an asynchronous function function
async function getPrice(){
// return the "promise" resulting from your chained method calls
return nightmare
.goto('https://uk.investing.com/commodities/real-time-futures')
.evaluate(()=>{
let gold = document.querySelector('.pid-68-last').innerText
let goldAug20 = document.querySelector('.pid-8830-last').innerText
let diff = Math.abs( gold.replace(',','') - goldAug20.replace(',',''))
return diff.toFixed(2)
})
.end()
.then(data =>{
price = data
//console.log(price)
return nightmare
})

}

// Make the callback asynchronous with the 'async' keyword
bot.on('message', async (msg) => {
// Use the 'await' keyword to pause execution until the promise
// is resolved (and therefore "price" is set)
await getPrice()
bot.sendMessage(msg.chat.id, price)
})
我不确定您的其余代码是否会按预期运行,但这就是您如何使异步工作按预期方式工作的方式!一定要花一些时间阅读 promises。他们需要练习来习惯,但是在Javascript中是必不可少的!

关于javascript - 为什么函数getPrice()仅调用一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62820685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com