title: Looping and Chaining Ajax Calls using deferred
body: <p>I've seen many questions about this but nothing seems to give the right answer for my case.
  I've seen also answers that uses <code>.pipe</code> but I'm looking for an answer that uses <code>.then</code>.</p>
  
  <p>Okay. I need to do 3 ajax calls, lets say a poll application that allows multiple accounts.
  The processes that need to be done so that an account can vote are the following.</p>
  
  <ol>
  <li>login</li>
  <li>select option/s</li>
  <li>submit</li>
  <li>logout(just clearing the cookies, no need to post).</li>
  </ol>
  
  <p>Let's say I have 2 accounts:</p>
  
  <pre><code>var accts = [{user: "acct1", pswd: "1234"},{user: "acct2", pswd: "4321"}];
  </code></pre>
  
  <p>Now I need to loop through those accounts using jquery's <code>$.each</code></p>
  
  <pre><code>$.each(accts, function(key,value){
  
  });
  </code></pre>
  
  <p>I learned that using <code>$.Deferred</code> can do this perfectly, but with correct implementation.</p>
  
  <p>What I want is</p>
  
  <pre><code>--------loop1--------
  login
  select
  vote
  --------loop2--------
  login
  select
  vote
  All Done!.
  </code></pre>
  
  <p>But what happens is (when i try to <code>console.log</code> on what is happening)
      All Done!
      login(2)
      select(2)
      vote(2)</p>
  
  <p>So here is my code:</p>
  
  <pre><code>$.each(data, function(k, v) {
      promise.then(function() {
          return $.post(loginURL, {user: v.username, passwrd: v.password});
      }).then(function(html) {
          if (data &gt; 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 a selection.');
              return false;
          } else {
              return $.post(pollURL + 'submit.php');
          }
      }).then(function(data){
           if(data &gt; 1) {
               Console.log('Successfully Voted.');
           } else {
             // if possible return to the login?
           }
      });
  });
  
  promise.done(function() {
      console.log('All Done. Logged out.');
  });
  </code></pre>
  
  <p>What am I doing wrong?.</p>