#Promise Practice
return new Promise((resolve, reject) => {
if(num > 10) {
resolve(`${num} is greater than 10`)
} else {
reject(Error(`${num} is less than 10`))
}
})
}
testNum(90)
.then(result => console.log(result))
.catch(err => console.error(err))
const words = ['cheese', 'bread', 'salami', 'apple'];
function makeAllCaps(words) {
return new Promise((resolve, reject) => {
if(words.every(val => typeof val === 'string')) {
resolve(words.map(word => word.toUpperCase()))
} else {
reject(Error('Strings only please!'))
}
})
}
function sortWords(words) {
return new Promise((resolve, reject) => {
resolve(words.sort())
})
}
makeAllCaps(words)
.then(words => sortWords(words))
.then(result => console.log(result))
.catch(err => console.error(err))
-
.then() is used to perform an action with a resolved promise object whereas .catch() is used to perform an action with a rejected promise.
-
Any kind of async code would be a good case for a promise but using it along side a fetch has been essential.
-
Promises can be used in frameworks like Angular and react as well as other libraries like jQuery.