Using WinJS I'm trying to display a message to the user who has just hit a 'continue' button that they haven't answered the question asked. That displays a dialog (Windows.UI.Popups.MessageDialog) with two buttons, which allow the user to choose to answer it now (and therefore stay on the uinaswered question) or answer it later (and therefore proceed straight to the next question). In Javascript, I could normally use a confirm dialog, which would halt execution until the user has made a selection and I could then use the returned value to decide whether or not to display the next question. In WinJS, code execution doesn't halt. Here's my function to display the dialog:
function doSillyMessage(message, title) {
var messagedialogpopup = new Windows.UI.Popups.MessageDialog(message, title);
// Add commands and set their CommandIds
messagedialogpopup.commands.append(new Windows.UI.Popups.UICommand("Answer now", null, 1));
messagedialogpopup.commands.append(new Windows.UI.Popups.UICommand("Answer later", null, 2));
// Set the command that will be invoked by default
messagedialogpopup.defaultCommandIndex = 0;
// Show the message dialog
messagedialogpopup.showAsync().done(function (command) {
if (command) {
if (command.id == 1) {
console.log('proceed in popup is false');
proceed = false;
}
else if (command.id == 2) {
console.log('proceed in popup is true');
proceed = true;
}
}
});
}
The problem is that at the point where doSillyMessage is called, the code doesn't wait and so continues with whatever the current value of the 'proceed' variable happens to be. For example, if the value of 'proceed' is false at the point where doSillyMessage is called, it is also false after doSillyMessage is called and is changed to true (if appropriate) only later, when I then see in the console 'proceed in popup is true'. How can I get this stuff to execute in the right order?
Dialogs are asynchronous; you'll need to wait on a promise in order to delay until the user's dealt with the input.
The easiest thing to do is to return the promise from your call to showAsync. Change this:
messagedialogpopup.showAsync().done(function (command) {
to
return messagedialogpopup.showAsync().then(function (command) {
if (command) {
if (command.id == 1) {
console.log('proceed in popup is false');
return false;
}
else if (command.id == 2) {
console.log('proceed in popup is true');
return true;
}
}
});
and change the call to doSillyMessage to:
doSillyMessage().then(function (proceed) {
// proceed will be true or false
});
Your callback logic has some holes in it; what do you return if command isn't set, or if it's not 1 or 2?