I am building an express.js
web application, and for one of the API requests I need to make multiple requests for multiple user accounts in parallel and return one object.
I tried using generators
and Promise.all
but I have 2 problems:
- I don't run in parallel for all user accounts.
- My code ends after the response has already returned.
Here is the code I wrote:
function getAccountsDetails(req, res) {
let accounts = [ '1234567890', '7856239487'];
let response = { accounts: [] };
_.forEach(accounts, Promise.coroutine(function *(accountId) {
let [ firstResponse, secondResponse, thirdResponse ] = yield Promise.all([
firstRequest(accountId),
secondRequest(accountId),
thirdRequest(accountId)
]);
let userObject = Object.assign(
{},
firstResponse,
secondResponse,
thirdResponse
);
response.accounts.push(userObject);
}));
res.json(response);
}