问题
I need to call some functions in sequence on form submit button click -
func1() -> func2() -> func3() ... -> func7() -> ...
All these functions do some kind of validation/checking and if validation fails, display a confirmation dialog to the user. If the user confirms, the next function in queue is executed.
Any of these functions could be doing some asynchronous task like sending Ajax request and depending on the result, showing the user some confirm dialog.
Details
I have asynchronous functions with the following structure -
function preValidateUrls(evt)
{
evt.preventDefault();
$.ajax({
type: "POST",
url: posturl+"?"+params,
dataType: "json",
success: function(res)
{
//display some confirmation dialog
if(confirm(msg))
{
$("form#frmBanners").submit();
}
}
});
}
How do I do this?
To begin with I just had two synchronous functions defined like this -
<form onsubmit="return func3()">
...
...
<input type="submit" onclick="return func1()"/>
</form>
func1() was being called at first, displaying confirmation dialog, then func2()...
Then I defined asynchronous function func2() (with the same structure as shown above) and called it like this -
$("input#formsubmitbutton").click(func2);
But, as expected, this does not wait for the confirmation of func1().
If I do like the following, the function
func2
gets called again and again -$('form#frmBanners').submit(function() { return func2(); //This is called after preValidateUrls() });
How do I do this in a clean way, so the tomorrow when I need to add any synchronous/asynchronous functions in between, I just need to edit at one place, something like -
func1() -> func2() -> func3() ... -> func7()
P.S. - I know, how to use callback functions in javascript.
回答1:
How about just one function in the submit handler:
<form action="" onsubmit="return func_test_all();">
</form>
Then inside your func_test_all()
you set up a Deferred pipe and return false;
at the end to prevent immediate form submission.
I have to run, so I don't have a complete code sample; I hope you can figure out the Deferred ;-) will only be back in 3 hours or so.
来源:https://stackoverflow.com/questions/10717982/correct-way-to-set-up-a-sequence-of-synchronous-asynchronous-functions-all-of-wh