Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

javascript - 如何更改Promise.all以一一发送请求(How to change Promise.all to send requests one by one)

I have a an array of chunked data that I need to upload one chunk at time.(我有一组分块的数据,我需要一次上传一个块。)

The current implementation I used it to encapsulate the logic in an Promise.all() since I need to return the result of the promise, The problem with this approach is that all the upload is done asynchronously resulting in a Timeout error as the server can't process all the requests at the same time, How can I modify this method so that the upload is done one chunk at time ?.(当前的实现中,我使用它将逻辑封装在Promise.all()中,因为我需要返回Promise的结果。这种方法的问题是所有上传都是异步完成的,导致服务器可能会发生Timeout错误不能同时处理所有请求,如何修改此方法,以便一次完成一个上传?) My code:(我的代码:) 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; } });   ask by Ahmed Chioua translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need them in SEQUENCE , for of is the way to go :(您需要在SEQUENCE中使用它们,因为方法是:)

async function chunksSequence(chunks) { for(const chunk of chunks) { await // your other code here } }; If you need to return something(如果您需要退货) async function chunksSequence(chunks) { let results = [] for(const chunk of chunks) { let result = await // your other code here results.push(result) } return results }; Because of comment needed in a promise on return(由于承诺退货时需要评论) 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) } };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...