2017-10-05 136 views
0

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

  1. first reference
  2. second reference

我想从第一参考获取数据,并使用DUID从第二参考获得的电子邮件。 问题是异步调用,我不能从一个表中获取数据并等待另一个表完成,我无法从第一个参考文献中获取所有数据,然后从第二个参考文献中获取所有数据,因为我在回这样的一个引用一个电话:

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

https://youtu.be/NgZIb6Uwpjc - 看看这个视频这恰恰说明了你的问题 –

回答

0

节点8已经支持异步/ 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找到一些例子。

0

你可以做到这一点使用嵌套.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)