1

I am trying to get data from database I have an array in which collection of id are present and i try to get data from a database for each id and then send to a client if try something like this:-

router.get('/getcart1', async (req, res) => {
  const email = req.body.email;`enter code here`
  const data = await cart1.find({ email: email });
  const id = data[0].id;

  let details = await id.map(async (e) => {
    console.log('start');
    console.log(e);
    let data = await books.find({ _id: e });
    console.log('end');
    return data;
  });
  res.json({ data: details });
});

the execution is start e start e end end ans when we send data details it show empty object i want all details.Inside a loop i have data but outside it show empty object

4
  • what is the value of data[0].id? You are treating it as an array by doing id.map but is it an array? Commented Apr 29, 2020 at 18:15
  • async functions return a promise. you can't use it like that. you can use await Promise.all(id.map ... ) Commented Apr 29, 2020 at 18:16
  • You cannot await an array of promises, you can only await a promise for an array. You're missing a Promise.all call. Commented Apr 29, 2020 at 18:17
  • actually there's definitely something else wrong with the code. Always Learning is probably right. JSON.stringify(await [Promise,Promise ... ]) should not return an empty object. Or maybe he meant [{},{} ...] as an empty object Commented Apr 29, 2020 at 18:26

1 Answer 1

2

You are trying to await an array of Promises, that's not going to work, you will need a Promise.all around this:

let details = await Promise.all(id.map(async (e) => {
  console.log('start');
  console.log(e);
  let data = await books.find({ _id: e });
  console.log('end');
  return data;
}));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.