skip to Main Content

I have a handler to handle a specific route in nodejs with express.

async function handleGetAllBookingByUserId(req, res, next) {
  try {
    let bookings = await pool.execute(queries.getAllBookingByUserId, [
      req.params.userId,
    ]);
    let map_ = await groupByBookings(bookings);
    console.log(map_.values());
    res.send(map_.values());
  } catch (err) {
    next(err);
  }
}

The function groupByBookings:

async function groupByBookings(bookings) {
  let map_ = new Map();
  for (let i = 0; i < (await bookings[0].length); i++) {
    let current = await bookings[0][i];
    let {
      bookingid,
      venueid,
      userid,
      bookingtimestamp,
      bookingstatus,
      paymenttype,
      price,
      timeslotstart,
      timeslotend,
      noofcourts,
    } = current;
    if (map_.has(current.id)) {
      map_.get(current.id).slots.push({ timeslotstart, timeslotend });
    } else {
      newObj = {
        bookingid,
        venueid,
        userid,
        bookingtimestamp,
        bookingstatus,
        paymenttype,
        price,
        noofcourts,
      };
      newObj.slots = [];
      newObj.slots.push({ timeslotstart, timeslotend });
      map_.set(bookingid, newObj);
    }
  }
  return map_;
}

When i console log i get the output but somehow , the Response is an empty object. I presume im doing something wrong with the async logic which im not sure of. Any help?

2

Answers


  1. Chosen as BEST ANSWER

    i was able to get the response as the Map.values() is an iterable.

    I had to pass the result as

    [...map_.values()]
    

    so something like

    res.send([...map_.values()])
    

  2. I don’t have enough reputation to comment, so this answer may not be 100% accurate.
    It seems to me that you have already resolved the promise in the handler:

    let bookings = await pool.execute(queries.getAllBookingByUserId, [
          req.params.userId,
    ]);
    

    So why would you await it again in the groupByBookings function?:

    for (let i = 0; i < (await bookings[0].length); i++) {
        let current = await bookings[0][I];
    

    It seems to me you can group the data without any need to await for it, maybe that’s what is confusing with the async logic

    Hope this helps

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search