When do nested promises need to be returned?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
When chaining multiple then statements, I'm struggling to understand when I need to return a value to the next then statement vs when it's automatically passed down. The confusion (for me) is when I have a promise inside a then statement vs not.
This is in a node environment - an express app (more specifically, a Firebase Function triggered by a HTTP request) - so I'll ultimately res.send() some value.
// Do I need to return mainFunction()?
mainFunction()
.then(resultOfMyFunction => {
// I want the next "then" to wait for the response from this block
// Do I have to return asyncFunction() or just the value below?
asyncFunction().then(resultOfPromise => {
// Do I return resultOfPromise?
}).catch(error => {
// If I return this error, will it go to the mainFunction catch block?
return error
})
}).then(resultOfPromise => {
// This is blocking, so the next "then" should wait for the value
return synchronousFunction(resultOfPromise)
}).then(resultOfSynchronousFunction => {
// End of function - do I need to return resultOfSynchronousFunction?
}).catch(error => {
// Do I need to return error?
})
I know we shouldn't nest promises, but Firebase doesn't really give us an option when you need to chain multiple, different database calls where each call is a promise and you need to wait for data from one to call the next.
javascript node.js promise
|
show 2 more comments
When chaining multiple then statements, I'm struggling to understand when I need to return a value to the next then statement vs when it's automatically passed down. The confusion (for me) is when I have a promise inside a then statement vs not.
This is in a node environment - an express app (more specifically, a Firebase Function triggered by a HTTP request) - so I'll ultimately res.send() some value.
// Do I need to return mainFunction()?
mainFunction()
.then(resultOfMyFunction => {
// I want the next "then" to wait for the response from this block
// Do I have to return asyncFunction() or just the value below?
asyncFunction().then(resultOfPromise => {
// Do I return resultOfPromise?
}).catch(error => {
// If I return this error, will it go to the mainFunction catch block?
return error
})
}).then(resultOfPromise => {
// This is blocking, so the next "then" should wait for the value
return synchronousFunction(resultOfPromise)
}).then(resultOfSynchronousFunction => {
// End of function - do I need to return resultOfSynchronousFunction?
}).catch(error => {
// Do I need to return error?
})
I know we shouldn't nest promises, but Firebase doesn't really give us an option when you need to chain multiple, different database calls where each call is a promise and you need to wait for data from one to call the next.
javascript node.js promise
The second outer.then()will not wait forasyncFunction()to complete if you don't return it from the first outer.then().
– Patrick Roberts
Nov 26 '18 at 15:31
The answer is don't nest promises. Chain them. if you doreturn asyncFunction();then thethencan live outside of the function and it's easier to read
– Liam
Nov 26 '18 at 15:32
So I would need to returnresultOfPromise, but do I also need to addreturnbeforeasyncFunction? Or will the second outer then wait forasyncFunctionautomatically?
– I'm Joe Too
Nov 26 '18 at 15:32
"will it wait automatically"...No. it will run that function and immediately run the nextthen()whereresultOfPromisewill be undefined
– charlietfl
Nov 26 '18 at 15:33
synchronousFunctionseems problematic. If this doesn't return a promise you need to wrap it in one if you want to consume if in this manner.
– Liam
Nov 26 '18 at 15:35
|
show 2 more comments
When chaining multiple then statements, I'm struggling to understand when I need to return a value to the next then statement vs when it's automatically passed down. The confusion (for me) is when I have a promise inside a then statement vs not.
This is in a node environment - an express app (more specifically, a Firebase Function triggered by a HTTP request) - so I'll ultimately res.send() some value.
// Do I need to return mainFunction()?
mainFunction()
.then(resultOfMyFunction => {
// I want the next "then" to wait for the response from this block
// Do I have to return asyncFunction() or just the value below?
asyncFunction().then(resultOfPromise => {
// Do I return resultOfPromise?
}).catch(error => {
// If I return this error, will it go to the mainFunction catch block?
return error
})
}).then(resultOfPromise => {
// This is blocking, so the next "then" should wait for the value
return synchronousFunction(resultOfPromise)
}).then(resultOfSynchronousFunction => {
// End of function - do I need to return resultOfSynchronousFunction?
}).catch(error => {
// Do I need to return error?
})
I know we shouldn't nest promises, but Firebase doesn't really give us an option when you need to chain multiple, different database calls where each call is a promise and you need to wait for data from one to call the next.
javascript node.js promise
When chaining multiple then statements, I'm struggling to understand when I need to return a value to the next then statement vs when it's automatically passed down. The confusion (for me) is when I have a promise inside a then statement vs not.
This is in a node environment - an express app (more specifically, a Firebase Function triggered by a HTTP request) - so I'll ultimately res.send() some value.
// Do I need to return mainFunction()?
mainFunction()
.then(resultOfMyFunction => {
// I want the next "then" to wait for the response from this block
// Do I have to return asyncFunction() or just the value below?
asyncFunction().then(resultOfPromise => {
// Do I return resultOfPromise?
}).catch(error => {
// If I return this error, will it go to the mainFunction catch block?
return error
})
}).then(resultOfPromise => {
// This is blocking, so the next "then" should wait for the value
return synchronousFunction(resultOfPromise)
}).then(resultOfSynchronousFunction => {
// End of function - do I need to return resultOfSynchronousFunction?
}).catch(error => {
// Do I need to return error?
})
I know we shouldn't nest promises, but Firebase doesn't really give us an option when you need to chain multiple, different database calls where each call is a promise and you need to wait for data from one to call the next.
javascript node.js promise
javascript node.js promise
edited Nov 26 '18 at 16:10
Gilad Bar
753314
753314
asked Nov 26 '18 at 15:28
I'm Joe TooI'm Joe Too
2,0801816
2,0801816
The second outer.then()will not wait forasyncFunction()to complete if you don't return it from the first outer.then().
– Patrick Roberts
Nov 26 '18 at 15:31
The answer is don't nest promises. Chain them. if you doreturn asyncFunction();then thethencan live outside of the function and it's easier to read
– Liam
Nov 26 '18 at 15:32
So I would need to returnresultOfPromise, but do I also need to addreturnbeforeasyncFunction? Or will the second outer then wait forasyncFunctionautomatically?
– I'm Joe Too
Nov 26 '18 at 15:32
"will it wait automatically"...No. it will run that function and immediately run the nextthen()whereresultOfPromisewill be undefined
– charlietfl
Nov 26 '18 at 15:33
synchronousFunctionseems problematic. If this doesn't return a promise you need to wrap it in one if you want to consume if in this manner.
– Liam
Nov 26 '18 at 15:35
|
show 2 more comments
The second outer.then()will not wait forasyncFunction()to complete if you don't return it from the first outer.then().
– Patrick Roberts
Nov 26 '18 at 15:31
The answer is don't nest promises. Chain them. if you doreturn asyncFunction();then thethencan live outside of the function and it's easier to read
– Liam
Nov 26 '18 at 15:32
So I would need to returnresultOfPromise, but do I also need to addreturnbeforeasyncFunction? Or will the second outer then wait forasyncFunctionautomatically?
– I'm Joe Too
Nov 26 '18 at 15:32
"will it wait automatically"...No. it will run that function and immediately run the nextthen()whereresultOfPromisewill be undefined
– charlietfl
Nov 26 '18 at 15:33
synchronousFunctionseems problematic. If this doesn't return a promise you need to wrap it in one if you want to consume if in this manner.
– Liam
Nov 26 '18 at 15:35
The second outer
.then() will not wait for asyncFunction() to complete if you don't return it from the first outer .then().– Patrick Roberts
Nov 26 '18 at 15:31
The second outer
.then() will not wait for asyncFunction() to complete if you don't return it from the first outer .then().– Patrick Roberts
Nov 26 '18 at 15:31
The answer is don't nest promises. Chain them. if you do
return asyncFunction(); then the then can live outside of the function and it's easier to read– Liam
Nov 26 '18 at 15:32
The answer is don't nest promises. Chain them. if you do
return asyncFunction(); then the then can live outside of the function and it's easier to read– Liam
Nov 26 '18 at 15:32
So I would need to return
resultOfPromise, but do I also need to add return before asyncFunction? Or will the second outer then wait for asyncFunction automatically?– I'm Joe Too
Nov 26 '18 at 15:32
So I would need to return
resultOfPromise, but do I also need to add return before asyncFunction? Or will the second outer then wait for asyncFunction automatically?– I'm Joe Too
Nov 26 '18 at 15:32
"will it wait automatically"...No. it will run that function and immediately run the next
then() where resultOfPromise will be undefined– charlietfl
Nov 26 '18 at 15:33
"will it wait automatically"...No. it will run that function and immediately run the next
then() where resultOfPromise will be undefined– charlietfl
Nov 26 '18 at 15:33
synchronousFunction seems problematic. If this doesn't return a promise you need to wrap it in one if you want to consume if in this manner.– Liam
Nov 26 '18 at 15:35
synchronousFunction seems problematic. If this doesn't return a promise you need to wrap it in one if you want to consume if in this manner.– Liam
Nov 26 '18 at 15:35
|
show 2 more comments
3 Answers
3
active
oldest
votes
I think you want something like this. I'm presuming that by This is blocking you mean synchronousFunction is not async. In which case it does not need to be consumed in a promise like fashion.
mainFunction()
.then(resultOfMyFunction => {
//return promise from async function
return asyncFunction();
})
.then(resultOfPromise => {
let resultOfSynchronousFunction = synchronousFunction(resultOfPromise);
// End of function
})
.catch(error => {
// Do I need to return error?
});
if you want to return resultOfSynchronousFunction then you should read How do I return the response from an asynchronous call?
If you want to return an async version of synchronousFunction you'll need to wrap this in a promise:
mainFunction()
.then(resultOfMyFunction => {
//return promise from async function
return asyncFunction();
})
.then(resultOfPromise => {
return new Promise((resolve, reject) => {
let resultOfSynchronousFunction = synchronousFunction(resultOfPromise);
// End of function
resolve(resultOfSynchronousFunction);
});
})
.then(resultOfSynchronousFunction => {})
.catch(error => {
// Do I need to return error?
});
If you want to run another async call after synchronousFunction a better pattern would be:
mainFunction()
.then(resultOfMyFunction => {
//return promise from async function
return asyncFunction();
})
.then(resultOfPromise => {
let resultOfSynchronousFunction = synchronousFunction(resultOfPromise);
// End of function
return anotherAsyncCall(resultOfSynchronousFunction );
})
.then(resultOfanotherAsyncCall => {})
.catch(error => {
// Do I need to return error?
});
But if I want to use the result ofsynchronousFunctionin the nextthenstatement, I canreturn synchronousFunction(resultOfPromise)and the nextthenwill be blocked untilsynchronousFunctionis done?
– I'm Joe Too
Nov 26 '18 at 15:40
2
In your code there is no nextthen? Promises (async functions) do not block. synchronous functions block. I'm not really clear what your getting at?
– Liam
Nov 26 '18 at 15:41
Sorry. If I want to useresultOfSynchronousFunctionin anotherthenblock (let's say I have three morethenstatements to run, that very nextthenblock will wait untilsynchronousFunctionis complete and I return that to the nextthen?
– I'm Joe Too
Nov 26 '18 at 15:44
3
I did not downvote, but wrapping the synchronous function in anew Promiseis an antipattern.
– trincot
Nov 26 '18 at 15:48
1
@Liam is right about what I was asking. How would I use the result of a synchronous function and pass that to the nextthenstatement if not via a promise?
– I'm Joe Too
Nov 26 '18 at 15:50
|
show 8 more comments
The confusion (for me) is when I have a promise inside a then statement vs not.
Whenever you have a promise inside a then or an async function you must return to it. Otherwise rejections (thrown errors in async functions and promises) get swallowed and end up in the global hook without giving a chance to whomever is calling your code to handle the error.
Synchronous functions have no such limitation - returning a synchronous code only matters if you want to reuse its return value since thrown errors are handled by the then automatically.
// If I return this error, will it go to the mainFunction catch block?
Promises are really quite non-magical. The return value is how the error/success (rejected/fulfilled) state is propagated between calls so if you don't return the value - mainFunction won't go to its catch block.
If you want it to go to its catch block - the return value needs to be a promise that eventually rejects - for that you need to either rethrow the error in the inner .catch block or remove the .catch from there altogether.
Appreciate the help! I was stuck on how to un-nest promises and the effect of synchronous functions insidethenstatements, but I get it now thanks to you and Liam's example.
– I'm Joe Too
Nov 26 '18 at 15:48
@trincot not misleading - just wrong, I missed that in the question. Fixing, thanks.
– Benjamin Gruenbaum
Nov 26 '18 at 15:53
@BenjaminGruenbaum: Could you provide a link or explanation why a promise inside a then (or async function) needs to be returned? I currently tried to "dispatch" a Promise whose result isn't of interest for me. So I just called it inside my async function without awaiting it (but try-catched it to log the error). The result is that my app just crashes without any error. And I really would like to know the mechanics behind the scenes. Thanks in advance!
– Newlukai
yesterday
That sounds weird and like some place in your code is throwing an error outside the call stack (like in a timer) - I'd recommend looking at the stack trace.
– Benjamin Gruenbaum
yesterday
Thanks for your support. And yes. After some changes I noticed that there is an error thrown. It is confusing that I don't get the usual "UnhandledPromiseRejection". Inside athenI call a function which returns a Promise. I add a catch call and don't return it. I was hoping that thus I would handle the rejection but don't need to wait for the Promise settlement to continue the outer Promise chain.
– Newlukai
yesterday
add a comment |
You don't really need the anonymous functions in the first two then()
You can do it by passing function references to then() instead
mainFunction()
.then(asyncFunction)
.then(synchronousFunction)
.then(resultOfSynchronousFunction => {
// consume resultOfSynchronousFunction or return to next then()
}).catch(error => {
// Do I need to return error?
// only if this is not final catch block
})
Appreciate the help!
– I'm Joe Too
Nov 26 '18 at 15:48
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53484355%2fwhen-do-nested-promises-need-to-be-returned%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
I think you want something like this. I'm presuming that by This is blocking you mean synchronousFunction is not async. In which case it does not need to be consumed in a promise like fashion.
mainFunction()
.then(resultOfMyFunction => {
//return promise from async function
return asyncFunction();
})
.then(resultOfPromise => {
let resultOfSynchronousFunction = synchronousFunction(resultOfPromise);
// End of function
})
.catch(error => {
// Do I need to return error?
});
if you want to return resultOfSynchronousFunction then you should read How do I return the response from an asynchronous call?
If you want to return an async version of synchronousFunction you'll need to wrap this in a promise:
mainFunction()
.then(resultOfMyFunction => {
//return promise from async function
return asyncFunction();
})
.then(resultOfPromise => {
return new Promise((resolve, reject) => {
let resultOfSynchronousFunction = synchronousFunction(resultOfPromise);
// End of function
resolve(resultOfSynchronousFunction);
});
})
.then(resultOfSynchronousFunction => {})
.catch(error => {
// Do I need to return error?
});
If you want to run another async call after synchronousFunction a better pattern would be:
mainFunction()
.then(resultOfMyFunction => {
//return promise from async function
return asyncFunction();
})
.then(resultOfPromise => {
let resultOfSynchronousFunction = synchronousFunction(resultOfPromise);
// End of function
return anotherAsyncCall(resultOfSynchronousFunction );
})
.then(resultOfanotherAsyncCall => {})
.catch(error => {
// Do I need to return error?
});
But if I want to use the result ofsynchronousFunctionin the nextthenstatement, I canreturn synchronousFunction(resultOfPromise)and the nextthenwill be blocked untilsynchronousFunctionis done?
– I'm Joe Too
Nov 26 '18 at 15:40
2
In your code there is no nextthen? Promises (async functions) do not block. synchronous functions block. I'm not really clear what your getting at?
– Liam
Nov 26 '18 at 15:41
Sorry. If I want to useresultOfSynchronousFunctionin anotherthenblock (let's say I have three morethenstatements to run, that very nextthenblock will wait untilsynchronousFunctionis complete and I return that to the nextthen?
– I'm Joe Too
Nov 26 '18 at 15:44
3
I did not downvote, but wrapping the synchronous function in anew Promiseis an antipattern.
– trincot
Nov 26 '18 at 15:48
1
@Liam is right about what I was asking. How would I use the result of a synchronous function and pass that to the nextthenstatement if not via a promise?
– I'm Joe Too
Nov 26 '18 at 15:50
|
show 8 more comments
I think you want something like this. I'm presuming that by This is blocking you mean synchronousFunction is not async. In which case it does not need to be consumed in a promise like fashion.
mainFunction()
.then(resultOfMyFunction => {
//return promise from async function
return asyncFunction();
})
.then(resultOfPromise => {
let resultOfSynchronousFunction = synchronousFunction(resultOfPromise);
// End of function
})
.catch(error => {
// Do I need to return error?
});
if you want to return resultOfSynchronousFunction then you should read How do I return the response from an asynchronous call?
If you want to return an async version of synchronousFunction you'll need to wrap this in a promise:
mainFunction()
.then(resultOfMyFunction => {
//return promise from async function
return asyncFunction();
})
.then(resultOfPromise => {
return new Promise((resolve, reject) => {
let resultOfSynchronousFunction = synchronousFunction(resultOfPromise);
// End of function
resolve(resultOfSynchronousFunction);
});
})
.then(resultOfSynchronousFunction => {})
.catch(error => {
// Do I need to return error?
});
If you want to run another async call after synchronousFunction a better pattern would be:
mainFunction()
.then(resultOfMyFunction => {
//return promise from async function
return asyncFunction();
})
.then(resultOfPromise => {
let resultOfSynchronousFunction = synchronousFunction(resultOfPromise);
// End of function
return anotherAsyncCall(resultOfSynchronousFunction );
})
.then(resultOfanotherAsyncCall => {})
.catch(error => {
// Do I need to return error?
});
But if I want to use the result ofsynchronousFunctionin the nextthenstatement, I canreturn synchronousFunction(resultOfPromise)and the nextthenwill be blocked untilsynchronousFunctionis done?
– I'm Joe Too
Nov 26 '18 at 15:40
2
In your code there is no nextthen? Promises (async functions) do not block. synchronous functions block. I'm not really clear what your getting at?
– Liam
Nov 26 '18 at 15:41
Sorry. If I want to useresultOfSynchronousFunctionin anotherthenblock (let's say I have three morethenstatements to run, that very nextthenblock will wait untilsynchronousFunctionis complete and I return that to the nextthen?
– I'm Joe Too
Nov 26 '18 at 15:44
3
I did not downvote, but wrapping the synchronous function in anew Promiseis an antipattern.
– trincot
Nov 26 '18 at 15:48
1
@Liam is right about what I was asking. How would I use the result of a synchronous function and pass that to the nextthenstatement if not via a promise?
– I'm Joe Too
Nov 26 '18 at 15:50
|
show 8 more comments
I think you want something like this. I'm presuming that by This is blocking you mean synchronousFunction is not async. In which case it does not need to be consumed in a promise like fashion.
mainFunction()
.then(resultOfMyFunction => {
//return promise from async function
return asyncFunction();
})
.then(resultOfPromise => {
let resultOfSynchronousFunction = synchronousFunction(resultOfPromise);
// End of function
})
.catch(error => {
// Do I need to return error?
});
if you want to return resultOfSynchronousFunction then you should read How do I return the response from an asynchronous call?
If you want to return an async version of synchronousFunction you'll need to wrap this in a promise:
mainFunction()
.then(resultOfMyFunction => {
//return promise from async function
return asyncFunction();
})
.then(resultOfPromise => {
return new Promise((resolve, reject) => {
let resultOfSynchronousFunction = synchronousFunction(resultOfPromise);
// End of function
resolve(resultOfSynchronousFunction);
});
})
.then(resultOfSynchronousFunction => {})
.catch(error => {
// Do I need to return error?
});
If you want to run another async call after synchronousFunction a better pattern would be:
mainFunction()
.then(resultOfMyFunction => {
//return promise from async function
return asyncFunction();
})
.then(resultOfPromise => {
let resultOfSynchronousFunction = synchronousFunction(resultOfPromise);
// End of function
return anotherAsyncCall(resultOfSynchronousFunction );
})
.then(resultOfanotherAsyncCall => {})
.catch(error => {
// Do I need to return error?
});
I think you want something like this. I'm presuming that by This is blocking you mean synchronousFunction is not async. In which case it does not need to be consumed in a promise like fashion.
mainFunction()
.then(resultOfMyFunction => {
//return promise from async function
return asyncFunction();
})
.then(resultOfPromise => {
let resultOfSynchronousFunction = synchronousFunction(resultOfPromise);
// End of function
})
.catch(error => {
// Do I need to return error?
});
if you want to return resultOfSynchronousFunction then you should read How do I return the response from an asynchronous call?
If you want to return an async version of synchronousFunction you'll need to wrap this in a promise:
mainFunction()
.then(resultOfMyFunction => {
//return promise from async function
return asyncFunction();
})
.then(resultOfPromise => {
return new Promise((resolve, reject) => {
let resultOfSynchronousFunction = synchronousFunction(resultOfPromise);
// End of function
resolve(resultOfSynchronousFunction);
});
})
.then(resultOfSynchronousFunction => {})
.catch(error => {
// Do I need to return error?
});
If you want to run another async call after synchronousFunction a better pattern would be:
mainFunction()
.then(resultOfMyFunction => {
//return promise from async function
return asyncFunction();
})
.then(resultOfPromise => {
let resultOfSynchronousFunction = synchronousFunction(resultOfPromise);
// End of function
return anotherAsyncCall(resultOfSynchronousFunction );
})
.then(resultOfanotherAsyncCall => {})
.catch(error => {
// Do I need to return error?
});
edited Nov 26 '18 at 15:51
answered Nov 26 '18 at 15:38
LiamLiam
16.5k1678131
16.5k1678131
But if I want to use the result ofsynchronousFunctionin the nextthenstatement, I canreturn synchronousFunction(resultOfPromise)and the nextthenwill be blocked untilsynchronousFunctionis done?
– I'm Joe Too
Nov 26 '18 at 15:40
2
In your code there is no nextthen? Promises (async functions) do not block. synchronous functions block. I'm not really clear what your getting at?
– Liam
Nov 26 '18 at 15:41
Sorry. If I want to useresultOfSynchronousFunctionin anotherthenblock (let's say I have three morethenstatements to run, that very nextthenblock will wait untilsynchronousFunctionis complete and I return that to the nextthen?
– I'm Joe Too
Nov 26 '18 at 15:44
3
I did not downvote, but wrapping the synchronous function in anew Promiseis an antipattern.
– trincot
Nov 26 '18 at 15:48
1
@Liam is right about what I was asking. How would I use the result of a synchronous function and pass that to the nextthenstatement if not via a promise?
– I'm Joe Too
Nov 26 '18 at 15:50
|
show 8 more comments
But if I want to use the result ofsynchronousFunctionin the nextthenstatement, I canreturn synchronousFunction(resultOfPromise)and the nextthenwill be blocked untilsynchronousFunctionis done?
– I'm Joe Too
Nov 26 '18 at 15:40
2
In your code there is no nextthen? Promises (async functions) do not block. synchronous functions block. I'm not really clear what your getting at?
– Liam
Nov 26 '18 at 15:41
Sorry. If I want to useresultOfSynchronousFunctionin anotherthenblock (let's say I have three morethenstatements to run, that very nextthenblock will wait untilsynchronousFunctionis complete and I return that to the nextthen?
– I'm Joe Too
Nov 26 '18 at 15:44
3
I did not downvote, but wrapping the synchronous function in anew Promiseis an antipattern.
– trincot
Nov 26 '18 at 15:48
1
@Liam is right about what I was asking. How would I use the result of a synchronous function and pass that to the nextthenstatement if not via a promise?
– I'm Joe Too
Nov 26 '18 at 15:50
But if I want to use the result of
synchronousFunction in the next then statement, I can return synchronousFunction(resultOfPromise) and the next then will be blocked until synchronousFunction is done?– I'm Joe Too
Nov 26 '18 at 15:40
But if I want to use the result of
synchronousFunction in the next then statement, I can return synchronousFunction(resultOfPromise) and the next then will be blocked until synchronousFunction is done?– I'm Joe Too
Nov 26 '18 at 15:40
2
2
In your code there is no next
then? Promises (async functions) do not block. synchronous functions block. I'm not really clear what your getting at?– Liam
Nov 26 '18 at 15:41
In your code there is no next
then? Promises (async functions) do not block. synchronous functions block. I'm not really clear what your getting at?– Liam
Nov 26 '18 at 15:41
Sorry. If I want to use
resultOfSynchronousFunction in another then block (let's say I have three more then statements to run, that very next then block will wait until synchronousFunction is complete and I return that to the next then?– I'm Joe Too
Nov 26 '18 at 15:44
Sorry. If I want to use
resultOfSynchronousFunction in another then block (let's say I have three more then statements to run, that very next then block will wait until synchronousFunction is complete and I return that to the next then?– I'm Joe Too
Nov 26 '18 at 15:44
3
3
I did not downvote, but wrapping the synchronous function in a
new Promise is an antipattern.– trincot
Nov 26 '18 at 15:48
I did not downvote, but wrapping the synchronous function in a
new Promise is an antipattern.– trincot
Nov 26 '18 at 15:48
1
1
@Liam is right about what I was asking. How would I use the result of a synchronous function and pass that to the next
then statement if not via a promise?– I'm Joe Too
Nov 26 '18 at 15:50
@Liam is right about what I was asking. How would I use the result of a synchronous function and pass that to the next
then statement if not via a promise?– I'm Joe Too
Nov 26 '18 at 15:50
|
show 8 more comments
The confusion (for me) is when I have a promise inside a then statement vs not.
Whenever you have a promise inside a then or an async function you must return to it. Otherwise rejections (thrown errors in async functions and promises) get swallowed and end up in the global hook without giving a chance to whomever is calling your code to handle the error.
Synchronous functions have no such limitation - returning a synchronous code only matters if you want to reuse its return value since thrown errors are handled by the then automatically.
// If I return this error, will it go to the mainFunction catch block?
Promises are really quite non-magical. The return value is how the error/success (rejected/fulfilled) state is propagated between calls so if you don't return the value - mainFunction won't go to its catch block.
If you want it to go to its catch block - the return value needs to be a promise that eventually rejects - for that you need to either rethrow the error in the inner .catch block or remove the .catch from there altogether.
Appreciate the help! I was stuck on how to un-nest promises and the effect of synchronous functions insidethenstatements, but I get it now thanks to you and Liam's example.
– I'm Joe Too
Nov 26 '18 at 15:48
@trincot not misleading - just wrong, I missed that in the question. Fixing, thanks.
– Benjamin Gruenbaum
Nov 26 '18 at 15:53
@BenjaminGruenbaum: Could you provide a link or explanation why a promise inside a then (or async function) needs to be returned? I currently tried to "dispatch" a Promise whose result isn't of interest for me. So I just called it inside my async function without awaiting it (but try-catched it to log the error). The result is that my app just crashes without any error. And I really would like to know the mechanics behind the scenes. Thanks in advance!
– Newlukai
yesterday
That sounds weird and like some place in your code is throwing an error outside the call stack (like in a timer) - I'd recommend looking at the stack trace.
– Benjamin Gruenbaum
yesterday
Thanks for your support. And yes. After some changes I noticed that there is an error thrown. It is confusing that I don't get the usual "UnhandledPromiseRejection". Inside athenI call a function which returns a Promise. I add a catch call and don't return it. I was hoping that thus I would handle the rejection but don't need to wait for the Promise settlement to continue the outer Promise chain.
– Newlukai
yesterday
add a comment |
The confusion (for me) is when I have a promise inside a then statement vs not.
Whenever you have a promise inside a then or an async function you must return to it. Otherwise rejections (thrown errors in async functions and promises) get swallowed and end up in the global hook without giving a chance to whomever is calling your code to handle the error.
Synchronous functions have no such limitation - returning a synchronous code only matters if you want to reuse its return value since thrown errors are handled by the then automatically.
// If I return this error, will it go to the mainFunction catch block?
Promises are really quite non-magical. The return value is how the error/success (rejected/fulfilled) state is propagated between calls so if you don't return the value - mainFunction won't go to its catch block.
If you want it to go to its catch block - the return value needs to be a promise that eventually rejects - for that you need to either rethrow the error in the inner .catch block or remove the .catch from there altogether.
Appreciate the help! I was stuck on how to un-nest promises and the effect of synchronous functions insidethenstatements, but I get it now thanks to you and Liam's example.
– I'm Joe Too
Nov 26 '18 at 15:48
@trincot not misleading - just wrong, I missed that in the question. Fixing, thanks.
– Benjamin Gruenbaum
Nov 26 '18 at 15:53
@BenjaminGruenbaum: Could you provide a link or explanation why a promise inside a then (or async function) needs to be returned? I currently tried to "dispatch" a Promise whose result isn't of interest for me. So I just called it inside my async function without awaiting it (but try-catched it to log the error). The result is that my app just crashes without any error. And I really would like to know the mechanics behind the scenes. Thanks in advance!
– Newlukai
yesterday
That sounds weird and like some place in your code is throwing an error outside the call stack (like in a timer) - I'd recommend looking at the stack trace.
– Benjamin Gruenbaum
yesterday
Thanks for your support. And yes. After some changes I noticed that there is an error thrown. It is confusing that I don't get the usual "UnhandledPromiseRejection". Inside athenI call a function which returns a Promise. I add a catch call and don't return it. I was hoping that thus I would handle the rejection but don't need to wait for the Promise settlement to continue the outer Promise chain.
– Newlukai
yesterday
add a comment |
The confusion (for me) is when I have a promise inside a then statement vs not.
Whenever you have a promise inside a then or an async function you must return to it. Otherwise rejections (thrown errors in async functions and promises) get swallowed and end up in the global hook without giving a chance to whomever is calling your code to handle the error.
Synchronous functions have no such limitation - returning a synchronous code only matters if you want to reuse its return value since thrown errors are handled by the then automatically.
// If I return this error, will it go to the mainFunction catch block?
Promises are really quite non-magical. The return value is how the error/success (rejected/fulfilled) state is propagated between calls so if you don't return the value - mainFunction won't go to its catch block.
If you want it to go to its catch block - the return value needs to be a promise that eventually rejects - for that you need to either rethrow the error in the inner .catch block or remove the .catch from there altogether.
The confusion (for me) is when I have a promise inside a then statement vs not.
Whenever you have a promise inside a then or an async function you must return to it. Otherwise rejections (thrown errors in async functions and promises) get swallowed and end up in the global hook without giving a chance to whomever is calling your code to handle the error.
Synchronous functions have no such limitation - returning a synchronous code only matters if you want to reuse its return value since thrown errors are handled by the then automatically.
// If I return this error, will it go to the mainFunction catch block?
Promises are really quite non-magical. The return value is how the error/success (rejected/fulfilled) state is propagated between calls so if you don't return the value - mainFunction won't go to its catch block.
If you want it to go to its catch block - the return value needs to be a promise that eventually rejects - for that you need to either rethrow the error in the inner .catch block or remove the .catch from there altogether.
edited Nov 26 '18 at 15:54
answered Nov 26 '18 at 15:43
Benjamin GruenbaumBenjamin Gruenbaum
192k65405441
192k65405441
Appreciate the help! I was stuck on how to un-nest promises and the effect of synchronous functions insidethenstatements, but I get it now thanks to you and Liam's example.
– I'm Joe Too
Nov 26 '18 at 15:48
@trincot not misleading - just wrong, I missed that in the question. Fixing, thanks.
– Benjamin Gruenbaum
Nov 26 '18 at 15:53
@BenjaminGruenbaum: Could you provide a link or explanation why a promise inside a then (or async function) needs to be returned? I currently tried to "dispatch" a Promise whose result isn't of interest for me. So I just called it inside my async function without awaiting it (but try-catched it to log the error). The result is that my app just crashes without any error. And I really would like to know the mechanics behind the scenes. Thanks in advance!
– Newlukai
yesterday
That sounds weird and like some place in your code is throwing an error outside the call stack (like in a timer) - I'd recommend looking at the stack trace.
– Benjamin Gruenbaum
yesterday
Thanks for your support. And yes. After some changes I noticed that there is an error thrown. It is confusing that I don't get the usual "UnhandledPromiseRejection". Inside athenI call a function which returns a Promise. I add a catch call and don't return it. I was hoping that thus I would handle the rejection but don't need to wait for the Promise settlement to continue the outer Promise chain.
– Newlukai
yesterday
add a comment |
Appreciate the help! I was stuck on how to un-nest promises and the effect of synchronous functions insidethenstatements, but I get it now thanks to you and Liam's example.
– I'm Joe Too
Nov 26 '18 at 15:48
@trincot not misleading - just wrong, I missed that in the question. Fixing, thanks.
– Benjamin Gruenbaum
Nov 26 '18 at 15:53
@BenjaminGruenbaum: Could you provide a link or explanation why a promise inside a then (or async function) needs to be returned? I currently tried to "dispatch" a Promise whose result isn't of interest for me. So I just called it inside my async function without awaiting it (but try-catched it to log the error). The result is that my app just crashes without any error. And I really would like to know the mechanics behind the scenes. Thanks in advance!
– Newlukai
yesterday
That sounds weird and like some place in your code is throwing an error outside the call stack (like in a timer) - I'd recommend looking at the stack trace.
– Benjamin Gruenbaum
yesterday
Thanks for your support. And yes. After some changes I noticed that there is an error thrown. It is confusing that I don't get the usual "UnhandledPromiseRejection". Inside athenI call a function which returns a Promise. I add a catch call and don't return it. I was hoping that thus I would handle the rejection but don't need to wait for the Promise settlement to continue the outer Promise chain.
– Newlukai
yesterday
Appreciate the help! I was stuck on how to un-nest promises and the effect of synchronous functions inside
then statements, but I get it now thanks to you and Liam's example.– I'm Joe Too
Nov 26 '18 at 15:48
Appreciate the help! I was stuck on how to un-nest promises and the effect of synchronous functions inside
then statements, but I get it now thanks to you and Liam's example.– I'm Joe Too
Nov 26 '18 at 15:48
@trincot not misleading - just wrong, I missed that in the question. Fixing, thanks.
– Benjamin Gruenbaum
Nov 26 '18 at 15:53
@trincot not misleading - just wrong, I missed that in the question. Fixing, thanks.
– Benjamin Gruenbaum
Nov 26 '18 at 15:53
@BenjaminGruenbaum: Could you provide a link or explanation why a promise inside a then (or async function) needs to be returned? I currently tried to "dispatch" a Promise whose result isn't of interest for me. So I just called it inside my async function without awaiting it (but try-catched it to log the error). The result is that my app just crashes without any error. And I really would like to know the mechanics behind the scenes. Thanks in advance!
– Newlukai
yesterday
@BenjaminGruenbaum: Could you provide a link or explanation why a promise inside a then (or async function) needs to be returned? I currently tried to "dispatch" a Promise whose result isn't of interest for me. So I just called it inside my async function without awaiting it (but try-catched it to log the error). The result is that my app just crashes without any error. And I really would like to know the mechanics behind the scenes. Thanks in advance!
– Newlukai
yesterday
That sounds weird and like some place in your code is throwing an error outside the call stack (like in a timer) - I'd recommend looking at the stack trace.
– Benjamin Gruenbaum
yesterday
That sounds weird and like some place in your code is throwing an error outside the call stack (like in a timer) - I'd recommend looking at the stack trace.
– Benjamin Gruenbaum
yesterday
Thanks for your support. And yes. After some changes I noticed that there is an error thrown. It is confusing that I don't get the usual "UnhandledPromiseRejection". Inside a
then I call a function which returns a Promise. I add a catch call and don't return it. I was hoping that thus I would handle the rejection but don't need to wait for the Promise settlement to continue the outer Promise chain.– Newlukai
yesterday
Thanks for your support. And yes. After some changes I noticed that there is an error thrown. It is confusing that I don't get the usual "UnhandledPromiseRejection". Inside a
then I call a function which returns a Promise. I add a catch call and don't return it. I was hoping that thus I would handle the rejection but don't need to wait for the Promise settlement to continue the outer Promise chain.– Newlukai
yesterday
add a comment |
You don't really need the anonymous functions in the first two then()
You can do it by passing function references to then() instead
mainFunction()
.then(asyncFunction)
.then(synchronousFunction)
.then(resultOfSynchronousFunction => {
// consume resultOfSynchronousFunction or return to next then()
}).catch(error => {
// Do I need to return error?
// only if this is not final catch block
})
Appreciate the help!
– I'm Joe Too
Nov 26 '18 at 15:48
add a comment |
You don't really need the anonymous functions in the first two then()
You can do it by passing function references to then() instead
mainFunction()
.then(asyncFunction)
.then(synchronousFunction)
.then(resultOfSynchronousFunction => {
// consume resultOfSynchronousFunction or return to next then()
}).catch(error => {
// Do I need to return error?
// only if this is not final catch block
})
Appreciate the help!
– I'm Joe Too
Nov 26 '18 at 15:48
add a comment |
You don't really need the anonymous functions in the first two then()
You can do it by passing function references to then() instead
mainFunction()
.then(asyncFunction)
.then(synchronousFunction)
.then(resultOfSynchronousFunction => {
// consume resultOfSynchronousFunction or return to next then()
}).catch(error => {
// Do I need to return error?
// only if this is not final catch block
})
You don't really need the anonymous functions in the first two then()
You can do it by passing function references to then() instead
mainFunction()
.then(asyncFunction)
.then(synchronousFunction)
.then(resultOfSynchronousFunction => {
// consume resultOfSynchronousFunction or return to next then()
}).catch(error => {
// Do I need to return error?
// only if this is not final catch block
})
answered Nov 26 '18 at 15:42
charlietflcharlietfl
142k1391125
142k1391125
Appreciate the help!
– I'm Joe Too
Nov 26 '18 at 15:48
add a comment |
Appreciate the help!
– I'm Joe Too
Nov 26 '18 at 15:48
Appreciate the help!
– I'm Joe Too
Nov 26 '18 at 15:48
Appreciate the help!
– I'm Joe Too
Nov 26 '18 at 15:48
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53484355%2fwhen-do-nested-promises-need-to-be-returned%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
The second outer
.then()will not wait forasyncFunction()to complete if you don't return it from the first outer.then().– Patrick Roberts
Nov 26 '18 at 15:31
The answer is don't nest promises. Chain them. if you do
return asyncFunction();then thethencan live outside of the function and it's easier to read– Liam
Nov 26 '18 at 15:32
So I would need to return
resultOfPromise, but do I also need to addreturnbeforeasyncFunction? Or will the second outer then wait forasyncFunctionautomatically?– I'm Joe Too
Nov 26 '18 at 15:32
"will it wait automatically"...No. it will run that function and immediately run the next
then()whereresultOfPromisewill be undefined– charlietfl
Nov 26 '18 at 15:33
synchronousFunctionseems problematic. If this doesn't return a promise you need to wrap it in one if you want to consume if in this manner.– Liam
Nov 26 '18 at 15:35