I'm following an example online:
const jeffBuysCake3 = cakeType => {
return new Promise((resolve, reject) => {
setTimeout(()=> {
if (cakeType
=== 'black forest') {
resolve('black forest cake!') //Callback function
} else {
reject('No cake 😢') //Callback function
}
}, 1000)
})
}
console.log(jeffBuysCake3('black forest').then(cake => console.log(cake)).catch(nocake => console.log(nocake)))
This returns black forest cake!
The part I don't understand is cake => console.log(cake)
What is cake in this example?
I understand that passing 'black forest' represents the parameter cakeType.
However It's not clear to me what 'cake' is.
Does cake = resolve?
Cake means the result of the successfully called promise, in this example they probably want to mean the cake result, and the cake result is a "black forest".
You could write it like this
jeffBuysCake3('black forest')
.then(result => console.log(result))
.catch(error => console.log(error))
and the result is going to be "black forest cake", if the promise function was like this
const jeffBuysCake3 = cakeType => {
return new Promise((resolve, reject) => {
setTimeout(()=> {
if (cakeType
=== 'black forest') {
resolve('Strawberry cake !') //Callback function
} else {
reject('No cake for you today') //Callback function
}
}, 1000)
})
}
the result is going to be "Strawberry Cake !", while if there was an error it would print out "No cake for you today".
In case you don't know how promises work, when we supply .then it means if the promise resolved (successfully) then give me back the result. If it couldn't be resolved, then catch the error which then we use .catch.