0

Whenever I hit this api with sending this

[{"project_id": "knsfviv9",
    "coach_id": ""
},
{"project_id": "ovsijiov9",
    "coach_id": ""
}]

it inserts into database but it gives response 0 as the result variable remains 0. result variable gets incremented but in res.send it sends 0. can someone help me with this?

app.post('/api/patc/:id', (req, res) => {
    let projectList = req.body;
    projectList.forEach(element => {
        let data = {
            patc_id: "patc-" + randomID(),
            college_id: req.params.id,
            project_id: element.project_id,
            coach_id: element.coach_id,
            date: NOW()
        };
        let sql = "INSERT INTO projects_assigned_to_colleges SET ?";
        conn.query(sql, data, (err, results) => {
            if (err) throw err;
            result.push(results);
        });
    });
    res.send(JSON.stringify({ "status": 200, "error": null, "response": result }));
});
Ekansh Jain
  • 100
  • 8
  • You're lucky that you get a response at all ;) `result` is a number and not an array: `result.push(results);` – Andreas Dec 30 '19 at 13:51
  • Your code initializes `result` to `0`, but then tries to use it as an array. Those calls to `.push()` should be resulting in an error. – Pointy Dec 30 '19 at 13:51
  • [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas Dec 30 '19 at 13:51

1 Answers1

0

You are trying to execute asynchronous code in forEach which is giving you undesired behavior. Change the code to something like this

app.post("/api/patc/:id", async (req, res) => {
  let projectList = req.body;
  var result = 0;
  const result = await Promise.all(projectList.map(element => {
    let data = {
      patc_id: "patc-" + randomID(),
      college_id: req.params.id,
      project_id: element.project_id,
      coach_id: element.coach_id,
      date: NOW()
    };
    return new Promise((resolve, reject) => {
      let sql = "INSERT INTO projects_assigned_to_colleges SET ?";
      conn.query(sql, data, (err, results) => {
        if (err) throw err;
        resolve(results);
      });
    });
  }));
  res.send(JSON.stringify({ status: 200, error: null, response: result }));
});

Ashish Modi
  • 7,529
  • 2
  • 20
  • 35