我有两个函数可以逐步完成一个简单的对话框树,使用 Impromptu 来获取用户输入。但是,由于 Impromptu 是异步的,因此不会等待用户的输入,并且功能会继续,不允许单步执行树。我知道我必须在 stepThroughTree 或 generateSingleTreeStep 中将其转换为使用回调或 Promise(尽管我不完全理解 Promise 的工作原理),但我不确定具体如何。下面列出了这两个函数以及示例树。
提前致谢
function generateSingleTreeStep(node) {
buttons = {};
var nextStep = false;
for (var option in node["options"]) {
var theOption = exampleTree["entry"]["options"][option];
buttons[theOption["text"]] = theOption["goal"];
}
$.prompt(node["text"], {
buttons: buttons,
submit: function (e, v, m, f) {
//This doesn't work - as the function ends, and stepThroughTree ends,
//returning false before the user can use the $.prompt
nextStep = v;//This is what I need to convert to a callback, as return
//nextStep is unable to get this value, and is console.log'ed as false.
}
});
console.log("Next Step: "+nextStep);
return nextStep;
}
function stepThroughTree(tree) {
if(tree["entry"]){
var nextNode = generateSingleTreeStep(tree["entry"]);
while(nextNode["options"]){
nextNode = generateSingleTreeStep(tree[nextNode]);
}
}
else{
console.error("Incorrectly configured node");
}
return false;
}
var exampleTree = {
entry: {
text: "Hey there neighbour!",
options: [
{
text: "Hey you",
goal: "friendly"
},
{
text: "Grr!",
goal: "unfriendly"
}
]
},
friendly: {
text: "You are a nice guy!",
options: false
},
unfriendly: {
text: "You are less nice",
options: false
}
};