Skip to content

Instantly share code, notes, and snippets.

@alexandrutapirdea
Created April 29, 2021 15:59
Show Gist options
  • Save alexandrutapirdea/48662af65ba939d29b922ae3a1a2a6ab to your computer and use it in GitHub Desktop.
Save alexandrutapirdea/48662af65ba939d29b922ae3a1a2a6ab to your computer and use it in GitHub Desktop.
Using Promises
const sonChecksWeather = new Promise(function (resolve, reject) {
setTimeout(() => {
const possibleOutcome = ['Sunny', 'Rainy', 'Unexpected error']
const randomNumber = Math.floor(Math.random() * 2)
const result = possibleOutcome[randomNumber]
console.log('Son: The weather is ', result)
// Both rainy or sunny will be on resolve
if (result === 'Sunny' || result === 'Rainy') {
resolve(result)
} else {
reject(new Error('I cannot tell how the weather will be'))
}
}, 2000)
})
const fatherWillDecide = sonChecksWeather
.then((weather) => {
if (weather === 'Sunny') {
console.log('We will go boating')
} else if (weather === 'Rainy') {
console.log('We will stay home and play boardgames')
}
})
.catch((error) => console.log('error is', error))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment