我正在尝试从Firebase设置一些变量,然后将这些变量传递给anotherfunction
。目前,Promise.all
正在正确设置foo
和bar
,但是,我无法判断foo
和bar
是否正在传递到then
并且Firebase的范围也不合适。
Promise.all
块基于以下教程: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');
}
});
如何将foo
和bar
传递到anotherFunction
并将该功能的响应设置为Firebase?
答案 0 :(得分:5)
这是您出错的地方 - 请参阅代码中的注释
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
})
要简化代码,只需删除}).then([foo, bar] => {
!!
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 ...
但是,如果实际代码比您显示的更多,则可以执行
return Promise.all([foo, bar])
.then(results => results.map(result => result.val()))
.then(([foo, bar]) => someModule.anotherFunction({
"foo": foo,
"bar": bar
}))
.then ...
或
return Promise.all([foo, bar])
.then(([foo, bar]) => ([foo.val(), bar.val()]))
.then(([foo, bar]) => someModule.anotherFunction({
"foo": foo,
"bar": bar
}))
.then ...
答案 1 :(得分:2)
then
中的添加
return Promise.resolve([foo,bar]);
或(根据@Jaromanda X)
return [foo, bar];