我根据时间范围在Firestore上有三个查询。 (24,12和6小时)。我正在使用Promise.all
并且它有效。从代码中可以看出,我通过使用返回快照的索引来访问每个查询的结果。我已经读过,无论完成顺序如何,返回的值都将按照传递的Promise的顺序排列。
现在,我希望能够将一个对象传递给Promise.all
,因为我的查询数量对于我想做的事情是不可预测的,基本上,我将循环到多个车辆并构建每个相同的3个查询,我将在Promise.all
上传递所有内容。当Promise.all
返回时,我希望能够知道该快照适用于哪个车辆和时间范围。
因此,我希望将此参数传递给Promise.all
而不是数组。
{"vehicle1_24":query, "vehicle1_12":query, "vehicle1_6":query,
"vehicle2_24":query, "vehicle2_12":query, "vehicle2_6":query}
码
var queries = [
vehicleRef.collection('telemetry').where('time_stamp', '<', today).where('time_stamp', '>', yesterday).get(),
vehicleRef.collection('telemetry').where('time_stamp', '<', today).where('time_stamp', '>', twelveHours).get(),
vehicleRef.collection('telemetry').where('time_stamp', '<', today).where('time_stamp', '>', sixHours).get()
]
for (var i = 0; i < queries.length; i++) {
queryResults.push(
queries[i]
)
}
Promise.all(queryResults)
.then(snapShot=> {
const yesterdayResult = result => getEnergy(result);
const twelveHourResult = result => getEnergy(result);
const sixHourResult = result => getEnergy(result);
allYesterdayResult += yesterdayResult(snapShot[0])
allTwelveHourResult += twelveHourResult(snapShot[1])
allSixHourResult +=sixHourResult(snapShot[2])
console.log("Done updating vehicle ", vehicle)
// return res.send({"Result" : "Successful!"})
}).catch(reason => {
console.log(reason)
// return res.send({"Result" : "Error!"})
答案 0 :(得分:4)
此功能本身并不存在,但应该相当容易编写,与
一致async function promiseAllObject(obj) {
// Convert the object into an array of Promise<{ key: ..., value: ... }>
const keyValuePromisePairs = Object.entries(obj).map(([key, valuePromise]) =>
valuePromise.then(value => ({ key, value }))
);
// Awaits on all the promises, getting an array of { key: ..., value: ... }
const keyValuePairs = await Promise.all(keyValuePromisePairs);
// Turn it back into an object.
return keyValuePairs.reduce(
(result, { key, value }) => ({ ...result, [key]: value }),
{}
);
}
promiseAllObject({ foo: Promise.resolve(42), bar: Promise.resolve(true) })
.then(console.log); // { foo: 42, bar: true }
答案 1 :(得分:-1)
您可以使用以下代码将对象转换为您将传递给Promise.all()的数组
var queriesObject = {"vehicle1_24":query, "vehicle1_12":query, "vehicle1_6":query, "vehicle2_24":query, "vehicle2_12":query, "vehicle2_6":query};
//Of course, queriesObject can be an oject with any number of elements
var queries = [];
for (var key in queriesObject) {
if (queriesObject.hasOwnProperty(key)) {
queries.push(queriesObject[key]);
}
}
Promise.all(queries);
您将在与查询数组相对应的履行值的数组中收到Promise.all的结果,请参阅:Promise.all: Order of resolved values和https://www.w3.org/2001/tag/doc/promises-guide#aggregating-promises < / p>