Skip to content

Instantly share code, notes, and snippets.

@troygoode
Last active August 29, 2015 14:11
Show Gist options
  • Select an option

  • Save troygoode/3aa2d35bfbdd8d104bbf to your computer and use it in GitHub Desktop.

Select an option

Save troygoode/3aa2d35bfbdd8d104bbf to your computer and use it in GitHub Desktop.
var Q = require('q');
function buildStructure(house) {
var deferred = Q.defer();
setTimeout(function () {
console.log('build structure');
// pretend like we're persisting this to a database
house.id = 'ABCD12345';
house.rooms = house.rooms || []; // make sure this is an array
deferred.resolve(house);
}, 1000);
return deferred.promise;
}
function paintHouse(house) {
var deferred = Q.defer();
setTimeout(function () {
console.log('paint the house');
house.color = "house-color";
deferred.resolve(house);
}, 1000);
return deferred.promise;
}
function buildRoom(room) {
var deferred = Q.defer();
setTimeout(function () {
room.id = 'ROOM_' + room.name.replace(/\D/g, '');
deferred.resolve(room);
}, 1000);
return deferred.promise;
}
function buildHouse(house) {
return Q.when(house)
.then(buildStructure)
.then(paintHouse)
.then(function(house) { // could replace this with `.get('rooms')` using Bluebird
return Q.all(house.rooms.map(buildRoom));
})
.then(function () { // could replace this with `.return(house)` using Bluebird
return house;
});
}
buildHouse({});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment