将对象参数传递给 Promise.all

was*_*898 0 node.js firebase google-cloud-firestore

我根据时间范围对 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}
Run Code Online (Sandbox Code Playgroud)

代码

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!"})
Run Code Online (Sandbox Code Playgroud)

Mad*_*iha 5

此功能本身并不存在,但应该很容易编写,类似于

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 }
Run Code Online (Sandbox Code Playgroud)