Skip to content

Instantly share code, notes, and snippets.

@niksumeiko
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niksumeiko/d1b40533582a93c4904b to your computer and use it in GitHub Desktop.
Save niksumeiko/d1b40533582a93c4904b to your computer and use it in GitHub Desktop.
Promises chaining that solves "callbacks hell"
'use strict';
var Promise = require('promise');
function build() {
return new Promise(function(fulfill, reject) {
fulfill('zero');
});
}
build().then(function(result) {
console.log(result); // `zero`
return 'one';
}).then(function(result) { // `one`
console.log(result);
return ['apple', 'banana', 'pear'];
}).then(function(result) {
console.log(result); // `['apple', 'banana', 'pear']`
// Returning anything inside promise fulfillment/rejection
// callbacks, creates a promise for you automatically
// offering executions chaining.
// This is exactly how promises are approaching to
// solve so popular "callbacks hell".
return {
name: 'Nik Sumeiko',
website: 'http://teamnik.org'
};
}).then(function(result) {
console.log(result); // `{ name: 'Nik Sumeiko', website: 'http://teamnik.org' }`
return build();
}).then(function(result) {
console.log(result); // `zero`
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment