Created
April 19, 2018 18:05
-
-
Save cklanac/4e834073a3c14611f5b394ca2e362114 to your computer and use it in GitHub Desktop.
promises demo
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'; | |
function coinFlip(delay) { | |
return new Promise((resolve, reject) => { | |
setTimeout(function () { | |
if (Math.round(Math.random())) { | |
resolve('Heads!'); | |
} else { | |
reject('Tails!'); | |
} | |
}, delay); | |
}); | |
} | |
const coin1 = coinFlip(100).catch(err => err); | |
const coin2 = coinFlip(200).catch(err => err); | |
const coin3 = coinFlip(300).catch(err => err); | |
Promise.all( [coin1, coin2, coin3] ) | |
.then(arrayOfResults => { | |
console.log(arrayOfResults); | |
}) | |
.catch(err => { | |
console.error(err); | |
}); | |
coinFlip(500) | |
.then(res => { | |
console.log(1, res); | |
return coinFlip(250); | |
}) | |
.then(res => { | |
console.log(2, res); | |
return coinFlip(750); | |
}) | |
.then(res => { | |
console.log(3, res); | |
return 'You Win!'; | |
}) | |
.then(res => { | |
console.log(4, res); | |
}) | |
.catch(err => { | |
console.error(err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment