如何更改Promise.all以一一发送请求

Ahm*_*oua 1 javascript promise typescript lodash

我有一组分块的数据,我需要一次上传一个块。当前的实现中,我使用它将逻辑封装在Promise.all()中,因为我需要返回Promise的结果。这种方法的问题是所有上传都是异步完成的,导致服务器可能会发生Timeout错误不能同时处理所有请求,如何修改此方法,以便一次完成一个上传?

我的代码:

var chunks = _.chunk(variableRecords, 30);
return Promise.all(
        chunks.map(chunk => this.portalService.updateDataForChart(variableId, chunk)))
        .then((updateRes: boolean[]) => {
          if (updateRes.every(updateStatus => updateStatus)) {
            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;
          }
        });

Run Code Online (Sandbox Code Playgroud)

Ren*_*laj 5

您需要在SEQUENCE中使用它们,因为方法是:

async function chunksSequence(chunks) {
  for(const chunk of chunks) {
    await // your other code here
  }
};
Run Code Online (Sandbox Code Playgroud)

如果您需要退货

async function chunksSequence(chunks) {
  let results = []
  for(const chunk of chunks) {
    let result = await // your other code here
    results.push(result)
  }
  return results 
};
Run Code Online (Sandbox Code Playgroud)

由于承诺退货时需要评论

async function chunksSequence(chunks) {
 return new Promise((resolve, reject)=>{
    let results = []
    for(const chunk of chunks) {
      let result = await // your other code here
      results.push(result)
    }
    resolve(results) 
  }
};
Run Code Online (Sandbox Code Playgroud)