0

I have a two functions that step through a simple dialog tree, using Impromptu to get user input. however, as Impromptu is asynchronous, the user's input is not waited for, and the functions continue, not allowing the tree to be stepped through. I know I have to convert it to use a callback or a promise (although I don't fully understand how promises work), either in stepThroughTree or generateSingleTreeStep, but am not sure exactly how. The two functions, along with an example tree, are listed below.

Thanks in advance

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
    }
};
Bob Eret
  • 59
  • 3
  • 12

0 Answers0