Skip to content

Instantly share code, notes, and snippets.

@boutell
Created March 8, 2018 16:14
Show Gist options
  • Save boutell/a6b5cb3ab0a25af0c121c53a743ae55f to your computer and use it in GitHub Desktop.
Save boutell/a6b5cb3ab0a25af0c121c53a743ae55f to your computer and use it in GitHub Desktop.
// Demonstration that promises do not involve the pyramid of doom.
// Native ES6 promises - you could do it with bluebird promises too,
// in which case Promise.delay is a built-in convenience method
function delays() {
return delay(100).then(function() {
return delay(100);
}).then(function() {
return delay(100);
}).then(function() {
return delay(100);
}).then(function() {
return delay(100);
});
}
// Use it to delay 5 times
delays().then(function() {
// Runs AFTER the delays
}).catch(function(e) {
// Runs if one of the delays throws an error
});
console.log('I run too soon because we did not use then');
// Let's actually implement delay since we're not using bluebird
function delay(msec) {
return new Promise(function(resolve, reject) {
setTimeout(resolve, msec);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment