Q-example

by Denise Nepraunig

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/q.js/0.9.2/q.min.js"></script>
http://joseoncode.com/2013/05/23/promises-a-plus/

JavaScript

/*
 * simulate an ajax operation to fetch a customer profile
 */

/*
.thenResolve(value) is the same as:

.then( function() {
    return value;
});

*/

function getUser (id) {
  return Q.delay(1000)
  .thenResolve({ id: id, name: 'user ' + id });
}

/*
 * simulate an asynchronous fetch from twitter.com
 */
function getTweets (user) { 
  return Q.delay(1000)
  .thenResolve([ { tweet: 'I love Q and Promises/A+' },
                 { tweet: 'I really love Q' } ]);
}

getUser(123)
  .then(getTweets) // => getTweets( return value from getUser )
  .then(function (tweets) {
    tweets.forEach(function(t){
      alert(t.tweet);
    });
  });