首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何访问承诺类的属性?

如何访问承诺类的属性?
EN

Stack Overflow用户
提问于 2018-05-07 15:23:17
回答 2查看 304关注 0票数 1

我有一个类,它有一个方法.I希望更改我的方法的返回类型。但是在承诺不能访问类的属性时,.how可以解决这个.But,得到这个异常

原因: TypeError:无法读取未定义的属性'bot‘

代码语言:javascript
复制
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;
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-07 15:29:49

您需要使用bind this或使用Arrow函数来保留this上下文:

代码语言:javascript
复制
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;
票数 2
EN

Stack Overflow用户

发布于 2018-05-07 15:29:56

这是可行的

代码语言:javascript
复制
sendText() {
    return new Promise((resolve, reject) => {
      console.log(this.bot); // it  will not be undefined
    });
  }

之所以这样做,是因为箭头函数通过词汇绑定它们的上下文,因此this实际上引用了原始上下文。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50217605

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档