Execute promise in synchronous batches javascript

ⅰ亾dé卋堺 提交于 2020-05-15 02:29:08

问题


I have a promise function that receives a row from rows array to a remote server.

const post = (row) => new Promise(resolve=>
    {    //do post then,
         resolve(response.data);
    }

So, I want to create a function that iterate through the array and execute post for each element in constant size batches. Before the execution of next batch, current batch should be resolved completely. How can I achieve this?


回答1:


can use Promise.all for the batch and await for resolve:

const post = (row) => new Promise(resolve => {
    setTimeout(
        () => resolve(row.id), //for demo purpose
        1000);
})

const rows = [{
    id: 1
}, {
    id: 2
}, {
    id: 3
}, {
    id: 4
}, {
    id: 5
}, {
    id: 6
}, {
    id: 7
}];

const execute = async (batchSize) => {
    let currentPtr = 0;
    while (currentPtr < rows.length) {
        const results = await Promise.all(
            rows.slice(currentPtr, currentPtr + batchSize)
            .map(row => post(row))
        )
        console.log(results);
        currentPtr += batchSize;
    }
}

execute(2);


来源:https://stackoverflow.com/questions/61442455/execute-promise-in-synchronous-batches-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!