jquery - Looping and Chaining Ajax Calls using deferred -
i've seen many questions nothing seems give right answer case. i've seen answers uses .pipe i'm looking answer uses .then.
okay. need 3 ajax calls, lets poll application allows multiple accounts. processes need done account can vote following.
- login
- select option/s
- submit
- logout(just clearing cookies, no need post).
let's have 2 accounts:
var accts = [{user: "acct1", pswd: "1234"},{user: "acct2", pswd: "4321"}]; now need loop through accounts using jquery's $.each
$.each(accts, function(key,value){ }); i learned using $.deferred can perfectly, correct implementation.
what want is
--------loop1-------- login select vote --------loop2-------- login select vote done!. but happens (when try console.log on happening) done! login(2) select(2) vote(2)
so here code:
$.each(data, function(k, v) { promise.then(function() { return $.post(loginurl, {user: v.username, passwrd: v.password}); }).then(function(html) { if (data > 0) { console.log('logged in!'); return $.post(pollurl + 'select.php', {id: 143}); } else { console.log('login failed.'); return false; } }).then(function(data) { if (data === 'selected') { console.log('already have selection.'); return false; } else { return $.post(pollurl + 'submit.php'); } }).then(function(data){ if(data > 1) { console.log('successfully voted.'); } else { // if possible return login? } }); }); promise.done(function() { console.log('all done. logged out.'); }); what doing wrong?.
ah, similar process struggled while. solution use .apply on jquery's .when process "unknown" number of ajax calls , resolve them all.
this isn't precisely need given situation, might give ideas how attack problem. tried state process in context of you're trying do,
var ajaxargs = [{id: 1, password: "qwerty"}, {id: 2, password: "zxcvb"}]; function dologin(id, pass) { return $.post("ws/path/here", {id: id, pass: pass}); } var logins = $.when.apply(null, ajaxargs.map(function(argset) { return dologin(argset.id, argset.password); }); logins.done(function(){ var logins = [].concat(arguments); logins.foreach(function(login) { //do vote //do logout }); });
Comments
Post a Comment