首页 > 解决方案 > 上传前如何拆分数据?

问题描述

我有一个将数据上传到服务器的功能,我需要对其进行修改以按块上传数据。

原函数实现如下:

    private async updateDatasource(variableName: string, variableRecords: ChartDataResponse[]):Promise<boolean> {
    // unrelated code
        return this.portalService.updateDataForChart(variableId, variableRecords)
            .then((updateRes: boolean) => {
                 if (updateRes) {
                    return this.executeRequest<HealthDataSource, boolean>({
                      path: `/variable/user/datasources/${dataSource.identifier}`,
                      method: 'PUT',
                      body: {
                        libelle: dataSource.datasource.libelle,
                        type: dataSource.datasource.type,
                        lastSyncDate: Math.max(maxDate, dataSource.datasource.lastSyncDate)
                      },
                      headers: this.getHeaders()
                    });
                  } else {
                    return false;
                  }
                });
            } else {
              return Promise.reject(false);
            }
          }

我尝试了以下方法,但似乎不知道如何返回带有结果的承诺:

    private async updateDatasource(variableName: string, variableRecords: ChartDataResponse[]): Promise<boolean> {
    //unrelated code 
    //chunked the data
          var chunks = _.chunk(variableRecords, 30);

          return _.forEach(chunks, (chunk) => this.portalService.updateDataForChart(variableId, chunk))
            .then((updateRes: boolean) => {
              if (updateRes) {
                return this.executeRequest<HealthDataSource, boolean>({
                  path: `/variable/user/datasources/${dataSource.identifier}`,
                  method: 'PUT',
                  body: {
                    libelle: dataSource.datasource.libelle,
                    type: dataSource.datasource.type,
                    lastSyncDate: Math.max(maxDate, dataSource.datasource.lastSyncDate)
                  },
                  headers: this.getHeaders()
                });
              } else {
                return false;
              }
            });
        } else {
          return Promise.reject(false);
     }
    }

标签: javascripttypescriptforeachpromiselodash

解决方案


您可以使用Promise.all()获取承诺结果列表

因此,在您的情况下,您希望生成一系列承诺,而不是使用 forEach 函数:

Promise.all(
   chunks.map(chunk => this.portalService.updateDataForChart(variableId, chunk)))...
).then(results => {
   // iterate over results array and do other stuff
})

推荐阅读