Skip to content

Instantly share code, notes, and snippets.

@chinmay185
chinmay185 / missing-return.js
Created April 13, 2015 13:23
missing return breaks the promise chain and causes subtle bugs
var q = require("q");
var getUser = function(username) {
return q.delay(500).then(function(){
return username + " user";
});
};
var getTweets = function(user) {
return q.delay(500).then(function(){
@chinmay185
chinmay185 / straighten-promises.js
Last active August 29, 2015 14:19
using q.all and q.spread to straighten promises
var q = require("q");
// v1
q.all([getUser(username1), getUser(username2)])
.then(function(users) {
makeFriends(users[0], users[1]);
});
// v2 (even better)
q.all([fetchUser(username1), fetchUser(username2)])
@chinmay185
chinmay185 / nested-promises.js
Last active August 29, 2015 14:19
do task1, do task2 and when both are done, do something else
fetchUser(username1)
.then(function(user1) {
fetchUser(username2)
.then(function(user2) {
makeFriends(user1, user2);
});
});
@chinmay185
chinmay185 / promise-land.js
Last active August 29, 2015 14:19
Flattening the promise chain. Writing promises in idiomatic style.
getUser("tom")
.then(getTweets)
.then(updateTimeline)
.then(function(){
console.log("done");
});
@chinmay185
chinmay185 / promise-hell.js
Last active August 29, 2015 14:18
Writing promises in callback style (ugly)
getUser("tom").then(function(user) {
getTweets(user).then(function(tweets) {
updateTimeline(tweets)
.then(function() {
console.log("done");
});
});
});