Javascript 为什么函数getPrice()只调用一次?

Javascript 为什么函数getPrice()只调用一次?,javascript,node.js,nightmare,Javascript,Node.js,Nightmare,为什么函数getPrice()在我的代码中只调用了一次?我认为它必须在每次电报机器人收到消息时调用。还是我错了 const Nightmare = require('nightmare') const nightmare = Nightmare({show: true}) const TelegramBot = require('node-telegram-bot-api') const TOKEN = '' const bot = new TelegramBot(TOKEN, {polli

为什么函数getPrice()在我的代码中只调用了一次?我认为它必须在每次电报机器人收到消息时调用。还是我错了

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()
,这是正确的,因此该事件可能只触发一次。可能会添加控制台日志,以验证事件是否在每条消息上触发

但是,代码还有一个问题,那就是
price
变量将在事件之后设置,因为它是异步的。我不熟悉噩梦库,但根据您的代码,您似乎可以对其进行一些简单的更改以使其正常工作:

//添加'async'关键字使其成为异步函数
异步函数getPrice(){
//返回链接方法调用产生的“承诺”
回归噩梦
后藤先生('https://uk.investing.com/commodities/real-time-futures')
.评估(()=>{
让gold=document.querySelector('.pid-68-last').innerText
让goldAug20=document.querySelector('.pid-8830-last').innerText
设diff=Math.abs(gold.replace(',','')-goldAug20.replace(',','')
回差固定(2)
})
(完)
。然后(数据=>{
价格=数据
//控制台日志(价格)
回归噩梦
})
}
//使用'async'关键字使回调异步
bot.on('message',async(msg)=>{
//使用'wait'关键字暂停执行,直到承诺生效
//已解决(因此设置了“价格”)
等待getPrice()
bot.sendMessage(msg.chat.id,price)
})

我不确定您的代码的其余部分是否会像预期的那样工作,但这就是您如何让异步内容按预期的方式工作的!一定要花点时间读一读。它们需要练习才能习惯,但在Javascript中是必不可少的

为什么不将bot.sendMessage调用移动到以msg.chat.id为参数的异步函数?这样,就不需要等待getPrice了。谢谢你,这对我很有帮助。现在函数被及时调用,但仍然是一次