【问题标题】:Cloud functions for Firebase: Update/Set using admin sdk which returns a promiseFirebase 的云功能:使用返回承诺的 admin sdk 更新/设置
【发布时间】:2017-09-25 23:47:29
【问题描述】:

在 Cloud Functions for Firebase 中,例如:

exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
    .onWrite(event => {
    //how to write data at another node and return promise?
    return admin.database().ref(`/abc/1234`).update({a:1}); //is this the correct way? 

})

https://firebase.google.com/docs/functions/get-started,它说

// You must return a Promise when performing asynchronous tasks inside a Functions such as
      // writing to the Firebase Realtime Database.
      // Setting an "uppercase" sibling in the Realtime Database returns a Promise.

但在https://firebase.google.com/docs/database/admin/save-data 中,api 正在使用回调。我可以知道如何正确设置/更新 firebase 函数中的数据吗?该代码将起作用,但我不确定我是否正确执行此操作,或者它是否是推荐的方式。谢谢。

【问题讨论】:

  • Firebase SDK 支持承诺和回调。有关更多详细信息,请参阅this blog post。简而言之——你上面写的应该可以工作!

标签: javascript firebase firebase-realtime-database google-cloud-functions


【解决方案1】:

Firebase 数据库 SDK 中的每个写入操作都会返回一个 Promise,以便您可以将其链接或返回到 Google Cloud Functions 环境。请参阅 Michael 提到的博文:Keeping our Promises (and Callbacks)

所以这两个代码 sn-ps 会做同样的事情。使用回调:

var ref = admin.database().ref(`/abc/1234`);
ref.update({a:1}, function(error) {
  if (!error) {
    console.log("Write completed")
  }
  else {
    console.error("Write failed: "+error)
  }
});

承诺:

var ref = admin.database().ref(`/abc/1234`);
ref.update({a:1}).then(function() {
  console.log("Write completed")
}).catch(function(error) {
  console.error("Write failed: "+error)
});

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 2018-04-19
    • 2019-03-07
    • 1970-01-01
    • 2020-03-21
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    相关资源
    最近更新 更多