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.