2 回答
TA贡献1846条经验 获得超7个赞
尝试
converse(msg: string) {
const userMessage = new Message(msg, 'user'); //gettng user message
this.update(userMessage);
var bot = new RiveScript({utf8: true}); // initializing bot
const loading_done = (bot) => ()=> {
console.log("Chatbot initialized!");
bot.sortReplies(); //sorting replies
let username = "user";
return bot.reply(username, msg).then(answer => { //getting chatbot answer
console.log("User: " + msg);
console.log("Chatbot: " + answer);
const result = answer;
const botMessage = new Message(result, 'bot');
this.update(botMessage);
});
}
bot.loadFile('/assets/brain/test.rive').then(loading_done(bot)); // loading bot brain
}
或者
loading_done(bot){
return ()=> {
const that = this;
console.log("Chatbot initialized!");
bot.sortReplies(); //sorting replies
let username = "user";
return bot.reply(username, msg).then(answer => { //getting chatbot answer
console.log("User: " + msg);
console.log("Chatbot: " + answer);
const result = answer;
const botMessage = new Message(result, 'bot');
that.update(botMessage);
});
}
}
converse(msg: string) {
const userMessage = new Message(msg, 'user'); //gettng user message
this.update(userMessage);
var bot = new RiveScript({utf8: true}); // initializing bot
bot.loadFile('/assets/brain/test.rive').then(this.loading_done(bot).bind(this)); // loading bot brain
}
但我相信第一个解决方案更清楚
TA贡献1817条经验 获得超6个赞
this使用箭头函数代替定义自己的上下文的函数:
const loading_done = () => {
console.log("Chatbot initialized!");
bot.sortReplies(); //sorting replies
let username = "user";
return bot.reply(username, msg).then(answer => { //getting chatbot answer
console.log("User: " + msg);
console.log("Chatbot: " + answer);
const result = answer;
const botMessage = new Message(result, 'bot');
this.update(botMessage);
});
}
当您使用打字稿时,您还可以将 loading_done 设为私有函数:
converse(msg: string) {
const userMessage = new Message(msg, 'user'); //gettng user message
this.update(userMessage);
var bot = new RiveScript({utf8: true}); // initializing bot
bot.loadFile('/assets/brain/test.rive').then(this.loadingDone); // loading bot brai
}
// Use camel case instead of snake case in typescript.
private loadingDone = () => {
console.log("Chatbot initialized!");
bot.sortReplies(); //sorting replies
let username = "user";
return bot.reply(username, msg).then(answer => { //getting chatbot answer
console.log("User: " + msg);
console.log("Chatbot: " + answer);
const result = answer;
const botMessage = new Message(result, 'bot');
this.update(botMessage);
});
}
添加回答
举报