The goal of this assignment is to familiarize ourselves with promises by writing functions that can (and should) be written without them. The functions below each take in an array and returns a promise. makeAllCaps()
capitolizes each element in an array and rejects if an element is not a string. sortWords()
sorts the elements alphabetically and also rejects if an element is not a string.
const array = ['wowow', 'pants', 'bird'];
const array2 = ['wowow', 5, 'bird'];
const makeAllCaps = (array) => {
return new Promise( (resolve, reject) => {
if (array.find(e => typeof e !== 'string') === undefined) {
resolve(array.map(word => word.toUpperCase()))
} else {
reject('No, the array you passed in contained an element that was not a string!')
}
});
}
const sortWords = (array) => {
return new Promise( (resolve, reject) => {
if (array.find(e => typeof e !== 'string') === undefined) {
resolve(array.sort())
} else {
reject('No, the array you passed in contained an element that was not a string!')
}
});
}
makeAllCaps(array)
.then(sortWords)
.then((result) => console.log(result))
.catch(error => console.log(error));
// [ 'BIRD', 'PANTS', 'WOWOW' ]
makeAllCaps(array2)
.then(sortWords)
.then((result) => console.log(result))
.catch(error => console.log(error));
// No, the array you passed in contained an element that was not a string!