I have an array of userIds that I use in getOrdersByUserId() to get the orders placed by these users for a specific month:
function getOrdersByUserId(userId, month = 4) {
const apiService = new ApiService();
return apiService.getOrdersList(`?OrderingUser=${userId}`)
.then(orders => {
const monthOrders = orders.filter(order => new Date(order.FromTime)
.getMonth() === month);
return monthOrders;
});
}
Here's getOrdersList() in ApiService:
getOrdersList(queryString = '') {
return httpsRequest.createRequest(this.URL.ordersList + queryString, {}, this.requestHeaders, 'GET')
.then(result => JSON.parse(result).Records);
}
httpsRequest.createRequest returns a promise that resolves with the response from the API (I can share that code too if necessary).
When I test getOrdersByUserId() with 8 userIds I have, I get the correct records every time. Where this breaks is when I put these calls into a promise chain and execute them with Promise.All(). I wrote the below code with help from this answer: Wait for forEach with a promise inside to finish
const promises = userIds.map(userId => {
return getOrdersByUserId(userId, month)
.then(orders => {
return orders;
});
});
Promise.all(promises).then(results => {
console.log(results);
}).catch(err => {
console.log(err);
});
Testing with the 8 userIds I get this error four or five times:
(node:1) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): SyntaxError: Unexpected end of JSON input
After a lot of console logging it seems that this error occurs when httpsRequest.createRequest() gives a result that is an empty string, instead of a JSON response from the API. So why would all of these calls with the same userIds work individually, but break when executed in a promise chain? How can I resolve this?