Как получить доступ к свойству класса в обещании? - PullRequest
0 голосов
/ 07 мая 2018

У меня есть класс, у которого есть один метод. Я хочу изменить тип возвращаемого значения моего метода. но в обещании не может получить доступ к свойствам класса. Как можно решить эту проблему. Но получить это исключение

Причина: ошибка типа: невозможно прочитать свойство 'bot' из неопределенного

const SDK = require('balebot');
const Promise = require('bluebird');

import incoming from './incoming';
const _ = require('lodash');

class Bale {
  constructor(bp, config) {
    if (!bp || !config) {
      throw new Error('You need to specify botpress and config');
    }
    this.bot = null;
    this.connected = false;
    this.bot = new SDK.BaleBot(config.botToken);
    bp.logger.info('bale bot created');
  }

  setConfig(config) {
    this.config = Object.assign({}, this.config, config);
  }


  sendText(chat, text, options) {
    let msg = new SDK.TextMessage(text);

    return new Promise(function (resolve, reject) {
      var response = this.bot.send(msg, receiver);
      if (response) {
        reject(err);
      } else {
        resolve(response);
      }
    });
  }


}

module.exports = Bale;

Ответы [ 2 ]

0 голосов
/ 07 мая 2018

Это будет работать

sendText() {
    return new Promise((resolve, reject) => {
      console.log(this.bot); // it  will not be undefined
    });
  }

Причина, по которой это работает, заключается в том, что функции стрелок лексически связывают свой контекст, поэтому this фактически ссылается на исходный контекст.

0 голосов
/ 07 мая 2018

Вам нужно bind this или использовать функции стрелки для сохранения this контекста:

const SDK = require('balebot');
const Promise = require('bluebird');

import incoming from './incoming';
const _ = require('lodash');

class Bale {
  constructor(bp, config) {
    if (!bp || !config) {
      throw new Error('You need to specify botpress and config');
    }
    this.bot = null;
    this.connected = false;
    this.bot = new SDK.BaleBot(config.botToken);
    bp.logger.info('bale bot created');
  }

  setConfig(config) {
    this.config = Object.assign({}, this.config, config);
  }


  sendText(chat, text, options) {
    let msg = new SDK.TextMessage(text);

    // Use an arrow function instead of function
    return new Promise((resolve, reject) => {
      var response = this.bot.send(msg, receiver);
      if (response) {
        reject(err);
      } else {
        resolve(response);
      }
    });
  }


}

module.exports = Bale;
...