【问题标题】:Firebase/nodeJS - fetch data from multiple firebase data referenceFirebase/nodeJS - 从多个 firebase 数据参考中获取数据
【发布时间】:2018-03-17 12:18:26
【问题描述】:

我正在构建一个从引用中获取数据的 json api,然后在引用数据中使用一个 ID,我需要从另一个引用中获取其他数据并将它们全部放入对象中。

  1. first reference
  2. second reference

我想从第一个引用中获取数据并使用 dUid 从第二个引用中获取电子邮件。 问题是异步调用,我不能只从一个表中获取数据并等待另一个表完成,我不能从第一个 ref 然后从第二个获取所有数据,因为我在一个回调这样的引用之一:

app.get('/trip-statistics', (request, response) => {
   tripRef.once('value').then(
     snap => response.status(200).send(extractTripInfo(snap))
   );
});

【问题讨论】:

标签: javascript json node.js firebase firebase-realtime-database


【解决方案1】:

Node 8 支持 async/await 语法,这应该让这变得相当容易:

// Note the `async` keyword in front of the function
app.get('/trip-statistics', async (request, response) => {

  // we'll wait for the first promise, its value will be put into the `tripValue` variable
  const trip = await tripRef.once('value').then(snap => snap.val())

  // whenever the trip is resolved, we will create a new promise, which depends on `trip.dUid`
  const driver = await driverRef.child(trip.dUid).once('value').then(snap => snap.val())

  // when both promises are fulfilled, we can tell the response to send both objects
  response.status(200).send({ trip, driver })
})

不要忘记捕捉错误,您可以在this article 中找到一些示例。

【讨论】:

    【解决方案2】:

    您可以使用嵌套的 .them 语句实现此目的

    app.get('/trip-statistics')
        .then(request, response) => {
        // add stuff from url1 response to url2
        return app.get('/driver'+ response.data[0].id)
      })
      .then(request, response) => {
        // add stuff from url2 response to url3
        return rp(url3)
      })
      .catch(err => console.log) 
    

    【讨论】:

      猜你喜欢
      • 2020-12-22
      • 2022-07-01
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 2020-06-20
      相关资源
      最近更新 更多