【问题标题】:How to split up data before upload?上传前如何拆分数据?
【发布时间】:2019-11-13 08:28:31
【问题描述】:

我有一个将数据上传到服务器的功能,我需要修改它以分块上传数据。

原函数实现如下:

    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);
     }
    }

【问题讨论】:

    标签: javascript typescript foreach promise lodash


    【解决方案1】:

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

    因此,在您的情况下,您不想使用 forEach 函数,而是要生成承诺数组:

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

    【讨论】:

    • 有没有办法可以为每个块创建一个承诺并将承诺链接起来?由于 Promise.all() 方法等待所有请求同时完成导致超时
    猜你喜欢
    • 2011-05-05
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 2018-01-18
    • 2018-11-11
    • 2011-03-19
    相关资源
    最近更新 更多