2017-10-05 132 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)