【问题标题】:Return a value from within .on() .once() call in Firebase for use in .then()从 Firebase 中的 .on() .once() 调用中返回一个值,以便在 .then() 中使用
【发布时间】:2021-04-01 05:20:54
【问题描述】:

我正在尝试从 firebase ref.on('value'ref.once('value' 调用中了解返回值; 所以我可以在后面的.then( 中使用从那里返回的值。 我试图从 例如ref.on('value', snap => { return 'Test Text or whatever'},我总是得到一个对象,其中.node_.value_ 将是来自firebase 调用的.val()。 对此行为的解释将不胜感激(目前我正在编写不整洁且令人费解的代码来完成工作,并希望避免这种情况)。

var ref = firebase.database().ref('myAddress/etc..');
ref.once('value', snap => {
  o0 = snap.val()
  console.log('In the once o0:')
  console.log(o0) // works perfectly
  // return 'Test text' // does not return the text
  // return o0 // does not return o0
}).then( in0 => {
  console.log(in0)
  console.log(`In the first then in0.node_.value_ is:`)
  console.log(in0.node_.value_)
  return in0.node_.value_
}).then( in1 => {
  console.log(`In the second then input was:`)
  console.log(in1) // here I begin to get what I want the value from: in0.node_.value_
  return 'Some text from custom then'
}).then( in0 => {
  console.log('In the third then input was:')
  console.log(in0) // this prints: 'Some text from custom then', as my sanity check
})

我试图真正理解这里发生了什么,所以我编写的代码是明智的。 我可以在 `on('value...' 调用中编写功能,但这不适用于我正在开发的应用程序的其他部分。 感谢 Firebase 文档中的解释甚至链接。

【问题讨论】:

  • 您没有在任何地方使用从once 返回的值。
  • 如果你指的是snap的值,我用它来获取o0然后console.log o0;问题是我可以从once 电话中返回其他内容吗?我做不到,也无法理解为什么不这样做。谢谢

标签: javascript firebase firebase-realtime-database promise


【解决方案1】:

要将ref.once('value') 用作promise,您应该省略第二个参数并直接转到.then

ref.once('value').then(snap => {
  o0 = snap.val()
  console.log('In the once o0:')
  console.log(o0) // works perfectly
  return o0 // does indeed return o0
}).then( in0 => {
  // ...
});

【讨论】:

  • 现在snap.val() 未定义,因此返回值也未定义。请注意,这里的snap 对象与ref.once('value', snap => 中的snap 完全不同。原型中没有函数.val()。谢谢
  • Documentation 建议这应该可行。
猜你喜欢
  • 2018-12-27
  • 2018-03-10
  • 2019-07-03
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
  • 2021-04-03
  • 1970-01-01
  • 2017-01-21
相关资源
最近更新 更多