我使用的是react ts,以nestjs作为后端。
上下文
我有一个函数 downloadZip(csvProps)
:输入-csv文件的参数和api请求的url;输出-包含4个csv文件的zip文件
const downloadZip = async (csvProps: any, urlParams: any) => {
let zip = new JSZip();
let csv = zip.folder("csv");
//English Data CSV
let enDataBlob = await downloadCSV(`${ServerService.getUrl()}/fetchData`, urlParams,
{...csvProps, filename: 'Data_en', columns: headers_data_en, wrapColumnChar: '"'})
csv?.file('Data_en.csv', enDataBlob as Blob, {base64: true})
//French Data CSV
let frDataBlob = await downloadCSV(`${ServerService.getUrl()}/fetchData`, urlParams,
{...csvProps, filename: 'Data_fr', columns: headers_data_fr, wrapColumnChar: '"'})
csv?.file('Data_fr.csv', frDataBlob as Blob, {base64: true})
//English Flow CSV
let enFlowBlob = await downloadCSV(`${ServerService.getUrl()}/fetchFlow`, urlParams,
{...csvProps, filename: 'Flow_en', columns: headers_flow_en, wrapColumnChar: '"'})
csv?.file('Flow_en.csv', enFlowBlob as Blob, {base64: true})
//French Flow CSV
let frFlowBlob = await downloadCSV(`${ServerService.getUrl()}/fetchFlow`, urlParams,
{...csvProps, filename: 'Flow_fr', columns: headers_flow_fr, wrapColumnChar: '"'})
csv?.file('Flow_fr.csv', frFlowBlob as Blob, {base64: true})
zip.generateAsync(({type: "blob"}))
.then((content) => {
saveAs(content, csvProps.filename)
})
}
这个 downloadCSV(url: string, urlParams: any, csvProps: any)
上面使用的函数只是向后端发出axios请求,并返回响应生成的csv blob:
export const downloadCSV = async (apiURL: string, urlParams: any, csvProps: any) => {
let csvBlob: Blob|undefined;
let api = await axios.get(apiURL, {
params: urlParams
})
.then(async (res) => {
// handleCSV: Gets all CSV related data and returns a csv Blob
csvBlob = await handleCSV({...csvProps, datas: res.data});
})
return csvBlob
}
因为我正在使用 async-await
,api请求和随后的blob生成过程按顺序进行,性能受到影响。
问题
有没有办法使这些过程并行?我希望所有的文件都被并行处理,然后最终添加到zip中。
1条答案
按热度按时间gj3fmq9x1#
而不是
await
通过调用每个api,您可以Promise.all(apiCalls)
并等待结果,让结果成为api返回的值数组。差不多