gpt4 book ai didi

javascript - 如何将 Promise.all 传递给另一个函数 Cloud Functions for Firebase

转载 作者:搜寻专家 更新时间:2023-11-01 00:14:09 27 4
gpt4 key购买 nike

我正在尝试从 Firebase 设置一些变量,然后将它们传递给 anotherfunction。目前,Promise.all 正在正确设置 foobar,但是,我无法判断 foobar 被传递到 then,并且 Firebase 的范围不正确。

Promise.all block 基于此处的教程: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');
}
});

如何将 foobar 传递给 anotherFunction 并将该函数的响应设置为 Firebase?

最佳答案

这里是你出错的地方——看代码中的注释

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] => { together!!

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 ...

关于javascript - 如何将 Promise.all 传递给另一个函数 Cloud Functions for Firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43959888/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com