Value of a variable remains unaltered when assigned during a loop

42 Views Asked by At

Edit: I'm doing away with pseudocode, here's the actual code.
I think the answer to question may lie here, but I can't understand the answer.

The value of searchedItem remains unaltered. The following is my actual code.

const searchedItem = async (req, res) => {
  const { requestedId } = req.query
  const client = await getClient()

  try {
    let searchedItem = 'literallyAnything'

    const allCollections = await db('dbName').listCollections().toArray()

    allCollections.forEach(async (collection) => {
      const allUnits = await client
        .db('dbName')
        .collection(collection.name)
        .find({})
        .toArray()

      for (const topic of allUnits) {
        if (typeof topic === 'object' && Object.keys(topic).length > 1) {
          for (const item in topic) {
            if (typeof topic[item] === 'object') {
              if (topic[item].id == requestedId) {
                searchedItem = await topic[item]
                break
              }
            }
          }
        }
      }
    })
    res.status(200).json(searchedItem)
  } catch (error) {
    // res.status(500).json(error)
  }
}

So, as mentioned above I read this answer, but I don't understand it.

To tackle the above, I decided to create another method whose sole job would be to send response to the frontend. And I decided to call it from the if statement itself, where I know the value of searchedItem still exists, which worked upto an extent. What I mean by that is, I do get the desired output in my browser, but additionally I also get the error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client, and my server crashes. I'm truncating the code for sake of brevity.

// The new method that I created
const sendResponse = (response, statusCode, data) => response.status(statusCode).json(data)
// Including only the modified if statement
if (topic[item].id == requestedId) {
  searchedItem = currentChild
  sendResponse(res, 200, searchedItem)
}

What change should I implement in my code? Thank you.

0

There are 0 best solutions below