如何正确创建具有异步启动属性的 JS 类?

问题描述 投票:0回答:1

对不起,复杂的解释:

我想以异步/等待的方式启动一个类实例,因为在构造函数中我们不允许使用异步/等待。所以我想也许我可以调用该类的静态异步方法,该方法将在填充类属性时启动并返回实例。

const ccxt = require('ccxt')
const Events = require('events')

class Exchange {
  constructor (platform, uid) {
    this.platform = platform
    this.uid = uid
    this.keys = {} // Should by asynchronously populated on class init
    this.exchange = null // Should pick a correct exchange platform
  }
  
  static async init (platform, uid) {
    this.instance = new Exchange(platform, uid)
    
    if (!this.keys || !this.keys[platform]) {
      await this.instance.fetchKeys(uid)
    }
    
    this.instance.setExchange(platform)
    
    return this.instance
  }
  
  async fetchKeys (uid) {
    // this.keys = database.findOne('settings', { user_id: uid })
    // FOLLOWING LINE IS TO SIMULATE A RESPONSE FROM DB
    this.keys = {
      binance: { key: 'apikey', secret: 'apisecret' },
      bybit: { key: 'apikey', secret: 'apisecret' },
      kukoin: { key: 'apikey', secret: 'apisecret' }
    }
  }
  
  setExchange (platform) {
    this.exchange = new ccxt[platform]({
      apiKey: this.keys[platform].key,
      secret: this.keys[platform].secret
    })
  }
}

然后我可以像这样得到那个类的实例:

const binance = await Exchange.init('binance', 111)
const bybit = await Exchange.init('bybit', 111)

App 正在监听 WebSocket 价格并发出服务器端事件 (SSE),因此我们可以监听它们并触发回调:

const onWsPriceEventCallback = async (event, bot) => {
  const { platform, symbol, price } = event

  if (bot.symbol === symbol && bot.platform_id === platform) {
    console.log(`Bot #${bot.id} - Platform requested: ${platform} - Platform received: ${Exchange.platform} - Price: ${price} ${symbol}`)
  }
}

// Here we listen for events
Events.on('price', (event) => onWsPriceEventCallback(event, bot))
我希望在 console.log 中得到的结果
Bot #1 - Platform requested: binance - Platform received: binance - Price: 28196.54 BTCUSDT
Bot #2 - Platform requested: bybit   - Platform received: bybit - Price: 28195.11 BTCUSDT
Bot #1 - Platform requested: binance - Platform received: binance - Price: 28196.97 BTCUSDT
相反,我在 console.log 中得到这个
Bot #1 - Platform requested: binance - Platform received: binance - Price: 28196.54 BTCUSDT
Bot #2 - Platform requested: bybit   - Platform received: bybit - Price: 28195.11 BTCUSDT
Bot #1 - Platform requested: binance - Platform received: bybit - Price: 28196.97 BTCUSDT // WRONG

如果请求的平台是“binance”,那么它应该收到“binance”而不是另一个。

有人能告诉我我的代码有什么问题吗?

node.js class asynchronous
1个回答
0
投票

Exhange.platform
正在访问类上的属性,每个只能有一个值。看起来它被设置为
binance
然后
bybit
然后根本没有改变。

我建议避免在 init 方法中使用

this
上下文存储值以清理逻辑,然后从那里开始。

例如:

  static async init (platform, uid) {
    const instance = new Exchange(platform, uid)
    
    if (!instance.keys || !instance.keys[platform]) {
      await instance.fetchKeys(uid)
    }
    
    instance.setExchange(platform)
    
    return instance
  }

这假设您只需要初始化异步字段并且不需要 Exchange 是单例。

© www.soinside.com 2019 - 2024. All rights reserved.