2 回答

TA貢獻(xiàn)1846條經(jīng)驗(yàn) 獲得超7個(gè)贊
嘗試
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
}
但我相信第一個(gè)解決方案更清楚

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超6個(gè)贊
this使用箭頭函數(shù)代替定義自己的上下文的函數(shù):
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);
});
}
當(dāng)您使用打字稿時(shí),您還可以將 loading_done 設(shè)為私有函數(shù):
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);
});
}
添加回答
舉報(bào)