0

I was looking at this other SO thread here: async/await with loop and wanted to do something similar with my code but unfortunately I can't see what the error is.

The groups value here is an array taken from req.body.allGroups. It doesn't seem to be performing any inserts at all into my my_groups postgres table.

app.post("/create-group", async (req, res) => {
  try {
    const groups = req.body.allGroups; 
    console.log(groups);

    for (const group of groups) {   
      console.log(group.groupName);
      let newGroup = await pool.query(       
        "INSERT INTO my_groups (id, group_name) VALUES($1, $2) RETURNING group_id",
            [ 99, group.groupName ]
      );
      res.json(newGroup.rows[0]);
    }

  } catch(err) {
    console.error(err.messasge);
  }
})

>>> UPDATED:

I have updated my code based on queries below and have also added console.log messages.

The console.log output after running the above updated code is as follows:

[
  {
    groupName: 'G1'
  },
  {
    groupName: 'G2'
  }
]
G1
undefined
tonyf
  • 34,479
  • 49
  • 157
  • 246
  • 1
    Are you sure `req.body.allGroups` contains a Promise? It's not impossible but quite unusual to see await on a property rather than on a function. – aleksxor May 27 '21 at 10:52
  • When you set res.json doesn’t that send a response back to the user, effectively ending the loop after one iteration – James May 27 '21 at 10:56
  • What's the actual problem? That `pool.query("INSERT ...")` doesn't create new entries? Then why the title? – Andreas May 27 '21 at 10:56
  • 30k (hence I guess at least some experience) and yet only a _"it doesn't seem to..."_? Check with the debugger, add `console.log()`s, ... – Andreas May 27 '21 at 10:58
  • "*I can't see what the error is*" - we can't see the log output either. Please be more specific about what doesn't work and what error messages you get. The "await in a loop" is fine per se. – Bergi May 27 '21 at 10:59
  • 2
    @James It doesn't end the loop. It just causes exceptions from the second iteration onwards. – Bergi May 27 '21 at 11:01
  • @Bergi Have updated my post and also provided sample output. Hope this helps. – tonyf May 27 '21 at 11:19
  • @Bergi I'm actually not getting any error just the output provided above and no actual inserts into postgres table occuring at all. – tonyf May 27 '21 at 11:26
  • The `undefined` would presumably come from the logged `err.messasge`. Try logging `err.message` (or just the whole `err`) instead. – Bergi May 27 '21 at 11:28
  • @Bergi by just console logging the whole `err` I managed to track that the issue was in fact a foreign key constraint violation that I have on the `my_groups` table. All good now and works a treat. I will place this as part of answering my own question. – tonyf May 27 '21 at 11:37
  • @Bergi - my only other question is, what is the best way to use `res.json(newGroup.rows[0]);` ? – tonyf May 27 '21 at 11:40
  • 1
    @tonyf Collect them into an array, respond with the array after the loop? I don't know what you're trying to achieve. – Bergi May 27 '21 at 12:24

3 Answers3

1
  1. you shouldnt do res.json() in the for loop. try putting it one ligne below, and adapt it, as the newGroup variable wont be reachable.

  2. await req.body.allGroups is not usual. unless your library needs this await should not be used.

  3. anyway, can you try to console.log(groups) before the loop to confirm that the data exist please. If yes, you have a problem in you pool.

  4. the catch part should do something like res.send('Error') or better : next(err); if you don't, the browser connexion will stay hanging.

Raphael PICCOLO
  • 2,095
  • 1
  • 12
  • 18
  • Have updated my post and also provided sample output. Hope this helps – tonyf May 27 '21 at 11:20
  • Could you please assist of where to place `res.json()` as outside of the loop, the `newGroup` variable is not defined? – tonyf May 27 '21 at 11:43
0

Some output would've been helpful. But i suggest you to debug the value of groups, i believe it stays empty, so the loop never runs, that's why nothing happens and you may not be getting may error. Also, await is supposed to be put in front of promise for which we want to wait. So make sure req.body.allGroups is a promise.

Jai Kumar
  • 38
  • 5
0

By just console logging the whole err I managed to track that the issue was in fact a foreign key constraint violation that I have on the my_groups table.

All good now.

tonyf
  • 34,479
  • 49
  • 157
  • 246