How can I gain access to an asynchronous response in synchronous code?
I've got a web page where I need a user to click the save button to save the content of the form back to the web server.
Part of the save is a check of items which may require a prompt to the user that allows them to confirm, edit and reorder items in a javascript popup.
If the prompt is required, I need to be able to access the response from the user, i.e. was the confirm or the cancel button clicked, if the cancel button was clicked, the save process must be stopped, if the confirm button was clicked the save process must continue:
Psuedo code for synchronous behaviour:
function SaveData()
{
if (itemsRequireValidation)
{
if (RESPONSE_CANCEL == ConfirmationDialog.Show()) {
return;
}
}
ProcessConfirmData(ConfirmationDialog.OutputData);
//...Do the rest of the save process
}
Given that:
The confirmation dialog is a Javascript object that builds some HTML output, there is asynchronous behaviour introduced by way of the fact that we cannot really continue the process until the user clicks either the confirm or the cancel b开发者_如何学Pythonuttons contained within the dialog.
That blocking code to make the Javascript wait until the user clicks one or the other will have negative behaviour that could either crash the browser or prevent the user from even clicking either of the buttons.
How can I go about refactoring this to take into account the fact that the dialog box is essentially asynchronous, but I need to process the user interaction as if it were synchronous?
I think really I just need to look at this from another point of view that right now I'm not seeing.
Use callbacks. Make your ConfirmationDialog
allow callback functions as options, it can call those functions when the user responds.
function SaveDate() {
function HandleSave() {
// process rest of save
}
if (itemsRequireValidation)
{
ConfirmationDialog.Show({
RESPONSE_CANCEL: function() {
// cancelled, do nothing
},
RESPONSE_OK: function(output) {
ProcessConfirmData(output);
HandleSave();
}
});
} else {
HandleSave();
}
}
I don't get why the dialog would be asynchronous. I guess I don't really understand what you're asking... In my view, it's simple:
- user clicks SAVE
- save routine checks for validation
- if needed, popup is generated, save is abandoned (nothing is asynchronous yet)
- when user confirms selection in popup, or popup is not needed, then initiate AJAX stuff.
Unless you are doing validation server-side, in which case,
- user clicks SAVE
- validation routine initiates AJAX, with success callback to, let's say,
validationResponse
validationResponse
gets a response saying whether save succeeded, or further edits are necessary- if not, you're done, stuff is saved
- if further edits are necessary, give the user a chance
- when user confirms the edits, redo from step 2.
精彩评论