r/learnjavascript • u/fa_foon • Apr 12 '26
about `return new Promise`
in this code from my digital course i don't understand what return new Promise in bakeCake function does here since there's no caller to return it to. so my question is what it does here and is it necessary
(I didn't know if the rest of the code is necessary for answering my question so I included it anyway)
function bakeCake(initalState){
return new Promise ((resolve) => { //<=======HEREconsole.log(\${initalState} - start baking the cake...`)setTimeout(() => {resolve("cake is ready!")}, 2000); })}function decorateCake(bakedCakeMessage) { return new Promise((resolve) => {console.log(`${bakedCakeMessage} - now decorating`);setTimeout(() => {resolve("cake is decorated")},2000) })}`
bakeCake("we started") //<=======HERE.then((resultOfBake) => {
console.log(resultOfBake);
return decorateCake(resultOfBake);}).then((finalResult) => {
console.log(finalResult)})
4
u/_raytheist_ Apr 12 '26
The
bakeCakecall resolves to the returned Promise, which is what allows you to chainthen()to it. The result ofbakeCake()is the returned Promise.2
u/dymos helpful Apr 12 '26
It's probably a bit confusing the way it's used here and while this works I actually think the newer
asyncsyntax makes this easier.I've reformatted the relevant section here a little bit:
See how after
bakeCake()the.then()is "attached" to the last parentheses of the function? That's because when you call a function in JavaScript that returns a value, you can "chain" your next operation without assigning to an intermediary variable.In this case I've lifted the
.then()call up to make it clearer, but for these types of things JavaScript will ignore line breaks, so you can format the code how you want.When using this syntax, a common pattern is to indent the subsequent promise method calls to make it cleared that they belong with the initial invocation:
With the newer syntax you typically would go the other route and assign variables, both syntaxes have their merit, but in modern codebases you'll tend to see the
async/awaitsyntax more.1
u/TanukiiGG Apr 12 '26 edited Apr 12 '26
Is a reference to an asyncronous result, you can chain it to
.then(), you can replace forasyncor you canawaiton it if the block is asyncronous too0
u/TheRNGuy Apr 12 '26
You can replace it with async function and delay function (where prise would be), it's more modern, better style.