Capturing Responses from Dialogs using MacOS JavaScript for Automation

I had to make my first dialog using MacOS’s JavaScript for Automation, and quickly ran into the question of how to capture its response. Take this example:

var choice = app.chooseFromList(["a","b","c","d"], {
    withTitle:"Hey you",
    withPrompt:"Select something",
    okButtonName:"Do It",
    cancelButton:"Spoilsport"
});

In JavaScript this would involve using either handler, something like:

choice.onSelect = function(event) {...}

Or it would involve a listener like:

choice.addEventListener("select", function(event){...});

In both cases, it’s still unclear where on the event I would get the response to tell me that a selection happened or that the dialog was cancelled. On a lark, I tried just querying my variable for the dialog (“choice” in this case), and found that the result was available directly from there. The resulting working code:

if(choice){
    response = choice;
} else {
    response = "user cancelled";
}

This syntax for what is ultimately asynchronous input is a bit crazy for any longtime JavaScript web programmer like myself. That said, I love the simplicity, and suspect that it’s more intuitive for someone without a history web programming.