如何传递Promise.all返回另一个函数Cloud Functions for Firebase

KVN*_*VNA 2 javascript node.js firebase google-cloud-functions

我试图从Firebase设置一些变量,然后将它们传递给一个anotherfunction.目前,Promise.all已正确设置foobar,但是,如果我不能告诉foobar被传递到then,而且火力地堡无法正常范围的.

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');
  }
});
Run Code Online (Sandbox Code Playgroud)

如何传递foobaranotherFunction和设置功能的响应火力?

Jar*_*a X 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
  })
Run Code Online (Sandbox Code Playgroud)

为了简化您的代码,只需删除}).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 ...
Run Code Online (Sandbox Code Playgroud)

但是,如果实际代码比你显示的更多,你可以做到

return Promise.all([foo, bar])
.then(results => results.map(result => result.val()))
.then(([foo, bar]) => someModule.anotherFunction({
    "foo": foo,
    "bar": bar
}))
.then ...
Run Code Online (Sandbox Code Playgroud)

要么

return Promise.all([foo, bar])
.then(([foo, bar]) => ([foo.val(), bar.val()]))
.then(([foo, bar]) => someModule.anotherFunction({
    "foo": foo,
    "bar": bar
}))
.then ...
Run Code Online (Sandbox Code Playgroud)