Skip to content

Instantly share code, notes, and snippets.

@attilavago
Created January 25, 2017 15:35
Show Gist options
  • Save attilavago/c7166b19aea46d387cd6718d03fc981b to your computer and use it in GitHub Desktop.
Save attilavago/c7166b19aea46d387cd6718d03fc981b to your computer and use it in GitHub Desktop.
Node.js ES6 Promises Example
new Promise(function(resolve, reject) {
setTimeout(function() {
var firstVal = 1;
// in the promise what you resolve is what gets returned
resolve(firstVal);
console.log('the initial promise renders: ', firstVal);
}, 3000); // faking some longer process
})
.then(function(firstVal) {
var secondVal = firstVal + 1;
console.log('the second function renders: ', secondVal);
return secondVal;
})
.then(function(secondVal) {
// note how each function uses a previous function's return value
var thirdVal = secondVal + 1;
console.log('the third function renders: ', thirdVal);
return thirdVal;
})
.then(function(thirdVal) {
// note how each function uses a previous function's return value
var fourthVal = thirdVal + 1;
console.log('the last function renders: ', fourthVal);
});
/* the resulting output should be:
the initial promise renders: 1
the second function renders: 2
the third function renders: 3
the last function renders: 4
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment