Created
March 8, 2018 16:14
-
-
Save boutell/a6b5cb3ab0a25af0c121c53a743ae55f to your computer and use it in GitHub Desktop.
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
// 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