Почему поля класса не проинициализированы?

Здравствуйте! Имеется следующий код:
import { Client } from 'service'; 
import Redis from 'ioredis';

import config from './config.js';

class ServiceFactory
{
    #client = null;
    #redis = null;

    #qr = null;
    #ready = false;
    #error = null;

    constructor()
    {
        this.#redis = new Redis(config.redis);
        this.init();
    }

    async init()
    {
        this.#client = new Client(await this.#loadSession());

        this.#client.on('auth_failure', this.#onFail);
        this.#client.on('ready', this.#onReady);
        this.#client.on('disconnected', this.#onFail);
        this.#client.on('qr', this.#onQr);

        this.#client.initialize();
    }

    #onFail(error_msg)
    {
        this.#ready = false;
        this.#error = error_msg;
    }

    #onReady()
    {
        this.#ready = true;
    }

    #onQr(qr_code)
    {
        this.#qr = qr_code;
    }

    async #loadSession()
    {
        const session = await this.#redis.get(config.service.redisKey);
        return JSON.parse(session);
    }

    async #saveSession(session)
    {
        return await this.#redis.set(config.service.redisKey,  JSON.stringify(session));
    }
}

export default ServiceFactory;


Возникает ошибка:
this.#qr = qr_code;
                 ^

TypeError: Cannot write private member #qr to an object whose class did not declare it


Получается из-за ассинхронного init() поля класса не успевают проинициализироваться? Как можно это исправить?
  • Вопрос задан
  • 77 просмотров
Решения вопроса 1
@psy667
Node.js backend developer
this в обработчике ссылается на класс Client, а не на ServiceFactory. Чтобы исправить можно сделать так
this.#client.on('qr', this.#onQr.bind(this));
либо сделать метод #onQr стрелочной функцией
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы