我有两个功能,通过一个简单的对话树,使用Impromptu获取用户输入。但是,由于Impromptu是异步的,用户的输入不会被等待,并且功能继续,不允许树被逐步通过。我知道我必须转换它以使用回调或承诺(虽然我不完全理解promises如何工作),无论是在stepThroughTree还是generateSingleTreeStep,但我不确定如何。下面列出了这两个函数以及一个示例树。
提前致谢
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
}
};