【发布时间】:2020-03-17 18:50:22
【问题描述】:
我正在构建一个 firebase 应用程序,用于计算存储在我的实时数据库中的“从”和“到”地址之间的通勤时间。我想调用一个 API 来计算每次通勤,并在计算完所有通勤时间后返回这些通勤时间。我第一次使用Promise.all 来构建这种行为。但是,最后,我只得到了我调用结果的空对象。有什么建议吗?
exports.updateCommutes = functions.https.onRequest((request, response) => {
const ref = admin.database().ref('/users/test_user/commutes');
return ref.once('value').then((snapshot)=>{
var urls = [];
const testURl = 'https://maps.googleapis.com/maps/api/distancematrix/json?key=XXXX&origins=Boston,MA&destinations=Cambridge,MA'; // I'm using a test API call for now
return Promise.all([fetch(testURl),fetch(testURl)])
.then((responses)=>{
return responses.map((res)=>res.json())
})
.then((data)=>{
console.log(data);// this prints out: [ Promise { <pending> }, Promise { <pending> } ]
return response.send(data);
})
})
.catch((error)=>console.log("error$"+error))
});
我的数据库如下所示:
icommute-firebase
- users
- - test_user
- - - commutes
- - - - M26JimVJ3P_nEvm1L6n
- - - - - from: Boston,MA
- - - - - to: Cambridge,MA
- - - - M26Joyu-rLGomY_oElm
- - - - M26JtYyvGK_fCx0FE-Q
- - - - M26Qhuc-gebRppy320c
使用 Postman 对 http://localhost:5001/icommute-firebase/us-central1/updateCommutes 的 GET 请求,结果:
[
{},
{}
]
当我期待时:
[
{
"destination_addresses": [
"Cambridge, MA, USA"
],
"origin_addresses": [
"Boston, MA, USA"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "4.9 km",
"value": 4925
},
"duration": {
"text": "16 mins",
"value": 978
},
"status": "OK"
}
]
}
],
"status": "OK"
},
{
"destination_addresses": [
"Cambridge, MA, USA"
],
"origin_addresses": [
"Boston, MA, USA"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "4.9 km",
"value": 4925
},
"duration": {
"text": "16 mins",
"value": 978
},
"status": "OK"
}
]
}
],
"status": "OK"
}
]
【问题讨论】:
-
请编辑问题以显示您数据库的相关内容,并描述您认为该函数应该返回给客户端的内容。
-
完成!现在有什么想法吗?
标签: firebase http firebase-realtime-database firebase-admin