So in my code I have a math equations that depends on an async call to Firebase. So when I get the values back I calculate the score inside a then statement, but I can’t get the function it’s inside to return the calculated value. So for instance if I have something like:
function parentFunction(){
let result = childFuntion()
}
function childFunction(){
let query = new Promise((resolve, reject) => {
let query = asyncFirebaseCall()
resolve(query)
}
Promise.all([listofQueries])
.then((res) => {
let result = _doMathStuff(listofQueries)
//I know this is not correct but im putting the return here
return result
}
}
how do i get the value of result inside the parent function?
2
Answers
The main issue is that you’re trying to return a value from an asynchronous operation as if it was synchronous. Instead, you should return a promise from childFunction and handle it in parentFunction.
My suggested code:
A few points:
asyncFirebaseCall() should return a promise.
I used Promise.all() even if there’s one promise for demonstration purposes. If you have multiple promises, you can add them in the array.
The promise inside childFunction is resolved with the result from the _doMathStuff function.
In the parentFunction, you call childFunction and handle its returned promise.
By doing this, you are correctly handling the asynchronous nature of your operations and can get the result of your calculations in the parentFunction when it’s ready.
I see two problems in your code at first glance:
return
statement inside yourchildFunction
function.then
inside yourparentFunction
function.And as Jaromanda already commented, you don’t need to construct your own
Promise
objects.So with those two fixed, the code would look like: