【发布时间】:2021-08-14 07:00:48
【问题描述】:
我有一个发出 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}
输出是:
(node:1282) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'body' of undefined
在我的 app.js 中:
priceChecker = new PriceCheck();
priceChecker.requestRateInterval("BTC", "USD", 0.01, 5000);
【问题讨论】:
-
alertDifference是如何定义的?你在构造函数中绑定requestRate吗? -
它被定义为类中的常规函数。在构造函数中绑定是什么意思?
-
它以标准方式定义,即不是特定于实例的
-
那么你需要在构造函数中绑定它,以便
this在你在其他实例方法中访问它时具有正确的值
标签: javascript node.js http asynchronous