How to make promise wait till all requests in a loop are completed?

Viewed 874

In project I use React+redux+fetch. I need to update 15 users and in order to update them I send request with user ids. On api side I have limit - 10 user can be updated per request, so I need to make 2 requests in order to update all users. in first request I send 10 ids in second 5 ids. After users updating I need to request userlist in order to update users info on the page. I perform promise:

let promise = new Promise(resolve => resolve(1));
let _this = this;
promise
                .then(() => {
                    let preparedIds = DataHelper.getArrayOfArrays(userIds, 10) ;
                   
                            for (let i = 1; i<preparedIds.length; i++) {
                                _this.props.dispatch(requestMeasurePermissions(preparedIds[i]))
                            }
                })
                .then(() => {
                    _this.props.dispatch(getUsersList())

                })

service method:

export function getArrayOfArrays(initialArray, subarraySize) {
    let subArrays = [];

    for (let i = 0; i<Math.ceil(initialArray.length/subarraySize); i++) {
        subArrays[i] = initialArray.slice((i*subarraySize), (i*subarraySize) + subarraySize)
    }

    return subArrays;
}

So I need to complete all requests in for-loop, and only after that to go to the next .then(), but my code does not work as _this.props.dispatch(getUsersList()) 'fires' after first cycle iteration, as a result I receive user list where 10 users are updated but another 5 not. How can I make promise to wait for the moment when all requests in the loop are performed?

1 Answers

Asynchronous execution in parallel (order of execution is unimportant, better performance):

Use Promise.all.

Asynchronous execution in series (order of execution is important, only start each request after the previous one resolves):

Use for await...of.

Related