javascript - 上传前如何拆分数据?
问题描述
我有一个将数据上传到服务器的功能,我需要对其进行修改以按块上传数据。
原函数实现如下:
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);
}
}
解决方案
因此,在您的情况下,您希望生成一系列承诺,而不是使用 forEach 函数:
Promise.all(
chunks.map(chunk => this.portalService.updateDataForChart(variableId, chunk)))...
).then(results => {
// iterate over results array and do other stuff
})
推荐阅读
- html - 根据父母填充颜色?
- javascript - 背景不会填满屏幕
- pic - EZBL_EraseAll 或 EZBL_NVMKEY 在 mplab x IDE 版本 5.4 中不起作用
- openid-connect - 如何处理 OIDC 服务器从 ASP.Net Core 应用程序关闭
- javascript - 将 json 数据传递到输入字段
- python-3.x - 如何使用 Selenium 和 Python 遍历 url 列表
- javascript - 如何将图像移至底部?
- svelte - 从商店发出 AJAX 请求
- python - python中所有ec2实例的csv输出
- python - 如何有效地循环字典,我应该使用另一种数据结构