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

时间:2017-05-14 02:43:58

标签: javascript node.js firebase google-cloud-functions

我正在尝试从Firebase设置一些变量,然后将这些变量传递给anotherfunction。目前,Promise.all正在正确设置foobar,但是,我无法判断foobar是否正在传递到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');
  }
});

如何将foobar传递到anotherFunction并将该功能的响应设置为Firebase?

2 个答案:

答案 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];