我正在构建一个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"
}
]
res.json()
还返回一个Promise。因此,您也需要处理它。请参阅以下示例:
const fetch = require('node-fetch');
const testURl = 'https://jsonplaceholder.typicode.com/todos/1'
return Promise.all([fetch(testURl),fetch(testURl)])
.then((responses)=>{
// res.json() returns a Promise.
// We need to wrap them again in Promise.all()
return Promise.all(responses.map((res)=>res.json()));
})
.then((data)=>{
console.log(data);
});
这将记录预期的输出:
[ { userId: 1,
id: 1,
title: 'delectus aut autem',
completed: false },
{ userId: 1,
id: 1,
title: 'delectus aut autem',
completed: false } ]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句