0

I have an object in my Node.js route (result), and I want to split that into two separate objects and return them both. However, sometimes the second object is returned empty and to fix that I want to make the function that splits it asynchronous. For some reason its not working though, what am I doing wrong? The function is separateResult().

EDIT: The problem seems to be in my createResponse(rows) function. My SQL query always returns 6 rows but my createResponse(rows) function sometimes returns an object with 5 key-value pairs instead of 6.

function createResponse(rows) {
  var response = {}
  var random = 0
  for (let i = 0; i < 6; i++) {
    var random = Math.floor(Math.random() * 101)
    response[random] = rows[i].user_name
  }
  return response
}
14
  • There's nothing asynchronous inside separateResult function. Remove the async keyword and call the function like you would call any other synchronous function. Also don't await the call to this function. Commented Oct 5, 2021 at 5:18
  • I did that and the problem still remains. I open up localhost:3000 and high is empty sometimes, and sometimes it isn't. Commented Oct 5, 2021 at 5:22
  • Log the result object and observe its value when separateResult function returns unexpected value. Commented Oct 5, 2021 at 5:23
  • Its empty, I'm pretty sure that res.send happens before the separateResult function can finish that's why high is empty sometimes. I believe the solution is to make the function asynchronous, I just don't know how to do that exactly. Commented Oct 5, 2021 at 5:31
  • What value of result are you passing to separateResult function as a parameter? Commented Oct 5, 2021 at 5:32

1 Answer 1

1

Because Math.random() sometimes generates same result. This can be any time 4/10, 3/5 ... anytime. Think of finding another way of giving key names to your response. E.G. you are using a loop. So i is always different. You can do response[rows[i].user_name+i]. Best practice would be using uuid library

Sign up to request clarification or add additional context in comments.

1 Comment

thank you so much brother, you are so smart! May Allah reward you. this was the solution. I fixed it by making the keys be the usernames (since they are all unique) and the values being the random numbers.

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.