首页 > 解决方案 > 为什么 firestore / AngularFire SDK 会为一个请求打包多个 Promise?

问题描述

这是我编写文档及其子集合的方式:

 public async setEvent(event: EventInterface): Promise<void[]> {
    return new Promise<void[]>(async (resolve, reject) => {
      const writePromises: Promise<void>[] = [];
      event.setID(event.getID() || this.afs.createId());
      event.getActivities()
        .forEach((activity) => {
          activity.setID(activity.getID() || this.afs.createId());
          writePromises.push(this.afs.collection('events').doc(event.getID()).collection('activities').doc(activity.getID()).set(activity.toJSON()));
          activity.getAllStreams().forEach((stream) => {
            this.logger.info(`Steam ${stream.type} has size of GZIP ${getSize(this.getBlobFromStreamData(stream.data))}`);
            writePromises.push(this.afs
              .collection('events')
              .doc(event.getID())
              .collection('activities')
              .doc(activity.getID())
              .collection('streams')
              .doc(stream.type) // @todo check this how it behaves
              .set({
                type: stream.type,
                data: this.getBlobFromStreamData(stream.data),
              }))
          });
        });
      try {
        await Promise.all(writePromises);
        await this.afs.collection('events').doc(event.getID()).set(event.toJSON());
        resolve()
      } catch (e) {
        Raven.captureException(e);
        // Try to delete the parent entity and all subdata
        await this.deleteEvent(event.getID());
        reject('Something went wrong')
      }
    })
  }

但是,当我查看网络选项卡时:

在此处输入图像描述

我看到一个请求启动了,到目前为止还不错,req_0数据是我的activity,但在同一个请求上进一步看,我可以看到:

在此处输入图像描述

所以它增加了更多的数据,这不应该发生,因为:a)我将请求的大小传递给 firestore(1mb)b)由于连接速度慢我超过了写入的时间限制。

最有趣的是,当我的网络速度较慢时会发生这种行为。

编辑:这是请求示例的有效负载:

在此处输入图像描述

任何人,来解释这是为什么?

标签: javascriptfirebasegoogle-cloud-firestore

解决方案


发生的是所谓的批处理,因此您的写入操作不会立即触发,它们将聚合为单个请求,因为执行网络 I/O 在时间和电池寿命方面是昂贵的。

最小化网络 I/O 可以节省电池寿命(如上所述),这实际上是主要问题。

引擎盖下发生了“魔术”


推荐阅读