Reputation: 907
I am trying to set a few variables from Firebase and then pass those into a anotherfunction
. Currently, the Promise.all
is properly setting foo
and bar
, however, I can't tell if foo
and bar
are being passed into then
, and also Firebase is not properly scoped.
The Promise.all
block is based on a tutorial found here: https://www.youtube.com/watch?v=NgZIb6Uwpjc&t=305s
exports.someFunction = functions.database.ref(`/data`).onWrite(event => {
const condition = event.data.val()
if (condition) {
// Get the data at this location only once, returns a promise, to ensure retrieval of foo and bar
const foo = event.data.adminRef.child('foo').once('value')
const bar = event.data.adminRef.child('bar').once('value')
return Promise.all([foo, bar]).then(results => {
const foo = results[0].val()
const bar = results[1].val()
// Properly sets foo and bar
// As far as I can tell foo and bar are not passed into 'then'
}).then([foo, bar] => {
return someModule.anotherFunction({
"foo": foo,
"bar": bar
})
})
} else {
console.log('Fail');
}
});
How can I pass foo
and bar
into anotherFunction
and set the response of that function to Firebase?
Upvotes: 3
Views: 3178
Reputation: 1
Here's where you've gone wrong - see the comments in the code
return Promise.all([foo, bar]).then(results => {
const foo = results[0].val()
const bar = results[1].val()
// you dont' return anything so, the following .then gets undefined argument
}).then([foo, bar] => {
// ^^^^^^^^^^^^^ invalid syntax, you need .then(([foo, bar]) =>
return someModule.anotherFunction({
"foo": foo,
"bar": bar
})
To simplify your code, just remove }).then([foo, bar] => {
altogether!!
return Promise.all([foo, bar])
.then(results => {
const foo = results[0].val()
const bar = results[1].val()
return someModule.anotherFunction({
"foo": foo,
"bar": bar
}))
.then ...
But, if there's more to the actual code than you show, you can do
return Promise.all([foo, bar])
.then(results => results.map(result => result.val()))
.then(([foo, bar]) => someModule.anotherFunction({
"foo": foo,
"bar": bar
}))
.then ...
or
return Promise.all([foo, bar])
.then(([foo, bar]) => ([foo.val(), bar.val()]))
.then(([foo, bar]) => someModule.anotherFunction({
"foo": foo,
"bar": bar
}))
.then ...
Upvotes: 6
Reputation: 3540
in the first then
add
return Promise.resolve([foo,bar]);
or (as per @Jaromanda X)
return [foo, bar];
Upvotes: 4