function retRGObj(objName, xTime) {
return new Promise(
function (resolve, reject) {
let data = {}
findR(objName, xTime).then(function (msg) {
data.R = msg
console.log(data) //--> saves the expected value
}).then(findG(objName, xTime).then(function (msg) {
data.G = msg
console.log(data) //--> saves the expected value
}))
console.log(data) //--> all values are gone, returned value is "Object {}"
resolve(data)
})
}
I don't know how I can not return the final value, it gets emptied in the last scope. How/why is it?
Presumably,
findR
andfindG
work asynchronously; otherwise, it would be weird that they return promises. So what you need to do is resolve your promise only when those promises complete. In your case, that would be within the callback tofindG(...).then
. Also, what you're passing intofindR(...).then
(the return value offindG
) is highly suspect.Here's a swing at it, but of course it depends on the details:
Or we can condense it further, because if an arrow function has just one expression in it and no
{}
around it, the result of that expression is its return value. So (not for the faint of heart!):That waits for
findR
to finish before startingfindG
; I don't immediately see why that would be necessary, as I don't see anything in the call tofindG
that relies on the results fromfindR
.If they can be in parallel, then updating my earlier version based on Bergi's comment, you can do this:
Or condensed: