// The code below executes a list of promises sequentially, so that the next request is only submitted
// after the previous one resolved. It returns a list with all the promise responses, in the same order
const sequentialPromises = promiseFactories => promiseFactories.reduce((acc, promiseFactory) => {
return acc.then((accumList) => {
return promiseFactory()
.then((serverResponse) =>
serverResponse.ok
? serverResponse.json()
: Promise.resolve({ error_code: 'SERVER_ERROR' })
)
.then((jsonResponse) => accumList.concat(jsonResponse));
});
}, Promise.resolve([]));
// HOW TO USE IT
const bookRoomsSequentially = (sessionKey, availState) => {
const requests = buildRoomRequests(sessionKey, availState);
const requestPromiseFactory = request => () => APIPost('/booking/basket/add/room/', request);
return sequentialPromises(requests.map(requestPromiseFactory));
};