I've hit a wall and can't seem to find a solution in the resources on Stack Overflow or Google. There must be something simple that I'm overlooking, maybe you could offer some help?
Here's the scenario:
- A JavaScript function is triggered by a click event and adds a new contact to our database.
- After successful creation, additional functions are called to adjust settings based on checkboxes.
- These calls are asynchronous, causing only the last function call to update the contact successfully.
- I can't get the calls to execute sequentially instead of concurrently.
- Each call returns a JsonResult upon completion (which is needed for other parts of the application).
The current code looks like this:
function CreateClicked() {
Contact.Create(<strong>**bunch of params**</strong>, function(data) {
if(data.success) {
togglePrimary(data.newId);
toggleBilling(data.newId);
toggleTechnical(data.newId);
toggleBalance(data.newId);
toggleSecurity(data.newId);
toggleMarketing(data.newId);
Modal.Load(<strong>**loads a modal view**</strong>);
}
});
}
The toggle functions look like this:
function togglePrimary(id) {
if ($("#contact_admin_primaryrole").prop('checked'))
{Contact.TogglePrimaryRole(id);}
}
This invokes a controller function that appears as follows:
public JsonResult TogglePrimaryRole(int contactId) {
try {
var c = new Contact(contactId);
c.IsPrimaryContact = !c.IsPrimaryContact;
c.Update(AuthenticatedUser.Username, !c.IsPrimaryContact);
return Json(JSONResponseFactory.SuccessResponse("Contact updated successfully"));
}
catch (Exception ex) {
return Json(JSONResponseFactory.ErrorResponse(ex.Message));
}
}
How should I structure this so that each toggle function waits for the previous one to finish and return a Json response, regardless of success?
Any suggestions?
Cheers, Dez