【问题标题】:How can I call a classes's other function inside a http request callback?如何在 http 请求回调中调用类的其他函数?
【发布时间】: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


【解决方案1】:

在你的构造函数中,你必须bind your instance methods 所以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 在您的实例方法的上下文中未定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多