我有一个类,它有一个方法.I希望更改我的方法的返回类型。但是在承诺不能访问类的属性时,.how可以解决这个.But,得到这个异常
原因: 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;发布于 2018-05-07 15:29:49
您需要使用bind this或使用Arrow函数来保留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;发布于 2018-05-07 15:29:56
这是可行的
sendText() {
return new Promise((resolve, reject) => {
console.log(this.bot); // it will not be undefined
});
}之所以这样做,是因为箭头函数通过词汇绑定它们的上下文,因此this实际上引用了原始上下文。
https://stackoverflow.com/questions/50217605
复制相似问题