Firebase云功能有时在功能结束前不会执行

时间:2018-02-05 04:47:54

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

如果我有这样的云函数,函数setData()总是会执行直到函数结束(控制台“成功设置数据!”或“无法设置数据”)?因为我以类似的方式设置了一个函数,它有时似乎在执行过程中停止执行。

function setData() {
  admin.database().ref(`someLocation`).set(true)
  .then(() => {
    return admin.database().ref(`anotherLocation`).set(true)
  }).then(() => {
    console.log("successfully set data!")
  }).catch(err => {
    console.log("could not set data", err)
  })
}


exports.newPotentialMember = functions.database.ref('listenLocation')
  .onCreate(event => {

    setData()

})

1 个答案:

答案 0 :(得分:4)

您现在没有从newPotentialMember返回任何值。这意味着,只要newPotentialMember返回,云功能就可以停止执行代码,这在setData 启动后会立即执行。由于写入数据库是异步发生的,因此必须从newPotentialMember返回一个在所有写入完成后解析的承诺。

function setData() {
  return admin.database().ref(`someLocation`).set(true)
  .then(() => {
    return admin.database().ref(`anotherLocation`).set(true)
  })
}


exports.newPotentialMember = functions.database.ref('listenLocation')
  .onCreate(event => {
    return setData()
})

我建议您仔细阅读Firebase documentation on synchronous functions, asynchronous functions, and promises

相关问题