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, mon
-
You have a common misunderstanding: You don't execute promises. Promise.all
doesn't "run" anything. A promise is just a means of watching an operation to know when it's done and whether it worked or failed.
In your case, the operations are started by apiService.getOrdersList
, as soon as you call it.
What you're seeing suggests that
The API service doesn't like you sending it eight simultaneous requests (perhaps it rate-limits), and
The promise from the API service resolves with a value that isn't valid JSON rather than rejecting when it can't handle #1 (which is unfortunate, it should reject, not resolve).
Nothing about using Promise.all
breaks these operations. But apparently, running eight of these operations in parallel breaks.
You could run them in series (one after another):
userIds.reduce((p, userId, index) => {
return p.then(results => {
return getOrdersByUserId(userId, month)
.then(orders => {
results[index] = orders;
return results;
});
});
}, Promise.resolve([]))
.then(results => {
// `results` is an array of results, in the same order as `userIds`
})
.catch(err => {
console.log(err);
});
Each call to getOrdersByUserId
waits for the previous one to complete; the final result is an array of results in the same order as the userIds
array.
讨论(0)
- 热议问题