如何在承诺中访问类的属性?

时间:2018-05-07 15:23:17

标签: node.js promise bluebird

我有一个有一个方法的类。我希望改变我的方法的返回类型来承诺。但是在promise中无法访问类的属性.how可以解决这个问题。但是得到这个异常

原因:TypeError:无法读取属性' 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 :(得分:1)

您需要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;

答案 1 :(得分:1)

这样可行

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

这个工作的原因是因为箭头函数在词法上绑定了它们的上下文,所以this实际上是指原始上下文。