【问题标题】:Async function not returning firebase object in componentWillMount异步函数未在 componentWillMount 中返回 firebase 对象
【发布时间】:2017-11-06 22:57:43
【问题描述】:

我正在构建一个 react 应用程序,该应用程序从 componentWillMount 中的 Firebase 检索 JSON 对象。我已经设置了一个异步函数来调用 Firebase,但是它不会随对象返回,而是返回回调函数本身。我对承诺有点困惑,需要澄清一下..

这是我的 getMessages 异步函数

import loadDB from './db';

// create a promise that returns snapshot.val
export default async (keyProp) => {
  try {
    const db = await loadDB()
    const key = db.ref('hashtags/' + keyProp)

    const response = await key.on('value', function(snapshot) {
      snapshot.val(); //Firebase Object displays in console.log here
    })

    return response
  }
  catch(err) {
    console.log('fetch failed', err);
    return null
  }
}

这是我的组件WillMount

import getMessages from '../lib/get-messages.js'

componentWillMount() {
        const key = this.props.url.query.name

        getMessages(key)
          .then(function(messages){

            // messages displays function (snapshot) {snapshot.val()}
            // in console.log instead of my firebase object 
            console.log('msgs', messages)
          })
      }

我认为这个问题与 const response 有关,它没有返回 firebase 对象..

【问题讨论】:

    标签: javascript reactjs firebase asynchronous firebase-realtime-database


    【解决方案1】:

    您需要从以下函数中获得return 值:

    const response = await key.on('value', function(snapshot) {
       // snapshot.val(); --> this need to be returned
       return snapshot.val();
    })
    

    【讨论】:

    • 已添加。但仍然得到相同的响应。
    猜你喜欢
    • 2020-06-28
    • 2019-02-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 2018-10-17
    • 2018-05-30
    • 2017-01-14
    • 2021-12-03
    相关资源
    最近更新 更多