如何在 http 请求回调中调用类的其他函数?



我有一个函数可以发出HTTP GET请求。这是我的";CheckPrice";班当我试图在回调中调用属于该类的另一个函数时,它会说它是未定义的。我该怎么办?

const got = require("got")

class PriceCheck {
constructor() {
this.lastTick;
this.requestTimerHandle
}
/**
* 
* get the absolute percent difference between two numbers
* 
* @param {*} firstNum 
* @param {*} secondNum 
* @returns 
*/
absolutePercentDiff(firstNum, secondNum) {
return ( Math.abs(firstNum - secondNum) / ((firstNum + secondNum) /2) ) * 100
}
/**
* send message to standard out if price difference too high
* 
* @param {*} currentTick 
* @param {*} threshold - a percent  
*/
alertDifference(currentTick, threshold) {
if (this.lastTick != undefined) {
let lastPrice = Number(lastTick.ask);
let currentPrice = Number(currentTick.ask);
let diff = this.absolutePercentDiff(lastPrice, currentPrice);
if (diff >= threshold) {
console.log("ALERT: price changed " + diff + " percent")
} 
}
this.lastTick = currentTick;
}

/**
* 
* @param {*} first first currency
* @param {*} second second currency
* @param {*} threshold % difference in prices from last retreival to send alert
* @param {*} interval how long to wait before retreiving price again
*/
requestRateInterval = function(first, second, threshold, interval) {
if (typeof this.requestTimerHandle != 'undefined') {
clearInterval(requestTimerHandle)
}
this.requestTimerHandle = setInterval(this.requestRate, interval, first, second, threshold)
}
async requestRate(first, second, threshold) {
console.log("requesting conversion rate between " + first + " and " + second)

try {
const response = await got('https://company.com/api' + first + '-' + second);
console.log(response.body);
let currentTick = JSON.parse(response.body);
this.alertDifference(currentTick, threshold);
} catch (error) {
console.log(error.response.body);
}
}
}
module.exports = {PriceCheck: PriceCheck}

输出为:

(节点:1282(未处理的PromiseRejection警告:类型错误:无法读取未定义的属性"body">

在我的app.js:中

priceChecker = new PriceCheck();
priceChecker.requestRateInterval("BTC", "USD", 0.01, 5000);

在构造函数中,您必须绑定实例方法,以便this在该实例方法的上下文中有一个值,如下所示:

constructor() {
this.lastTick;
this.requestTimerHandle;
// Bound instance methods
this.absolutePercentDiff = this.absolutePercentDiff.bind(this);
this.alertDifference = this.alertDifference.bind(this);
this.requestRateInterval = this.requestRateInterval.bind(this);
this.requestRate = this.requestRate.bind(this);
}

否则,this在实例方法的上下文中是未定义的。

最新更新