Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promises with lodash

I am trying to generate a list of users with _.times but I get an array of Promised objects. How do I output an array of plain objects?

const createUser = async () => ({

});

const users = [];

_.times(5, () => users.push(createUser()));

Promise.all(users);

Output

[ Promise { { username: 'Armando', password: '8cw0W7Jpm0LSSS9' } },
  Promise { { username: 'Lauren', password: '9oFCK4rqLj_DGol' } },
  Promise { { username: 'Frederique', password: 'JXGOsjCCOMFBYFd' } },
  Promise { { username: 'Otilia', password: 'DnxArNIsjaVoMB2' } },
  Promise { { username: 'Elisabeth', password: 'kZbSlg7bVWiagFT' } } ]

Expected

[
  { username: 'Armando', password: '8cw0W7Jpm0LSSS9' },
  { username: 'Lauren', password: '9oFCK4rqLj_DGol' },
  { username: 'Frederique', password: 'JXGOsjCCOMFBYFd' },
  { username: 'Otilia', password: 'DnxArNIsjaVoMB2' },
  { username: 'Elisabeth', password: 'kZbSlg7bVWiagFT' }
]
like image 738
Chris Meek Avatar asked Jul 08 '18 12:07

Chris Meek


2 Answers

You can get it in the then callback of Promise.all:

Promise.all(users).then(result => {
  console.log(result);
});
like image 69
Jonas Wilms Avatar answered Sep 20 '22 19:09

Jonas Wilms


Just await the result of Promise.all:

const users = await Promise.all(userPromises)

EDIT

Using await will of course only work inside an async function -- thx for pointing that out in the comments Olian02.

like image 23
dr_barto Avatar answered Sep 21 '22 19:09

dr_barto