How to pass a Promise.all return to another function Cloud Functions for Firebase
firebase, google-cloud-functions, javascript, node.js
Solution
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 ...
Problem
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?