Last active
August 29, 2015 14:23
-
-
Save niksumeiko/d1b40533582a93c4904b to your computer and use it in GitHub Desktop.
Promises chaining that solves "callbacks hell"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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