javascript - Preforming 2 async functions on success -


i have case create new user via ajax call, , after user created (server returns 200), update again ajax.

now can in stupid way have ajax call written 2 times:

  1. when create user
  2. inside success: of first ajax

that way call synchronous. i'm looking more elegant way of preforming ajax call, preferably ajax inside function recieves url , data values , call when first execution successful.

this have now:

var requests = [     {url: 'addnewuser', data: ''},     {url: 'updateuser', data: ''} ];     requests[0].data = json.stringify(formdata); formdata.roles = "4,2,30"; requests[1].data = json.stringify(formdata); for(var k=0;k<requests.length;k++){     $.ajax({         type: "post",         url: apiurl + requests[k].url,         contenttype: "application/json",         data: requests[k].data,         success: function(data) {             console.log(data + " success");         },         error: function(data) {             console.log("error " + data);         },         done: function(data) {             console.log(data + " success");         }     }); } 

right now, updateuser finishes before addnewuser, fails because there's no user update.

don't use for loop; instead, use callback earlier call start next call (see *** lines). note there no done option $.ajax; there's done function can call on $.ajax result, we're using below, want complete option:

var requests = [     {url: 'addnewuser', data: ''},     {url: 'updateuser', data: ''} ];     requests[0].data = json.stringify(formdata); formdata.roles = "4,2,30"; requests[1].data = json.stringify(formdata); var k = 0; doone();                                    // *** function doone() {                          // ***     if (k >= requests.length) {         return;     }     $.ajax({         type: "post",         url: apiurl + requests[k].url,         contenttype: "application/json",         data: requests[k].data,         success: function(data) {             console.log(data + " success");         },         error: function(data) {             console.log("error " + data);         },         complete: function(data) {          // ***             console.log(data + " complete");// ***             ++k;                            // ***             doone();                        // ***         }     }); } 

if want "loop" continue when earlier calls successful, move ++k; , doone(); calls complete success.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -