Javascript 如何将函数转换为异步使用回调

Javascript 如何将函数转换为异步使用回调,javascript,asynchronous,impromptu,Javascript,Asynchronous,Impromptu,我有两个函数,通过一个简单的对话框树,使用即兴获得用户输入。但是,由于Impromptu是异步的,因此不等待用户的输入,函数将继续,不允许遍历树。我知道我必须将其转换为使用回调或承诺(尽管我不完全理解承诺是如何工作的),无论是在stepThroughTree还是generateSingleTreeStep中,但我不确定具体是如何工作的。下面列出了这两个函数以及一个示例树 提前谢谢 function generateSingleTreeStep(node) { buttons = {};

我有两个函数,通过一个简单的对话框树,使用即兴获得用户输入。但是,由于Impromptu是异步的,因此不等待用户的输入,函数将继续,不允许遍历树。我知道我必须将其转换为使用回调或承诺(尽管我不完全理解承诺是如何工作的),无论是在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
    }
};

建议:尽可能多地使用
Promise
s。如果您想通过回调并被允许使用libs,它会起作用。否-它是否有帮助的功能?