Home > Enterprise >  ExpressJS res send before database loop request
ExpressJS res send before database loop request

Time:09-09

I have a postgres database. It contains records that have a column that refers to other similar records. The column format is JSON. So I get a record, it has links to other records. Such nesting can be n quantity. Therefore, I cannot know in advance how many requests I will need. The fact is that all these requests must be made through an asynchronous method, since I use the "pg" library. But res.send is a synchronous method and it is executed on the stack before the first iteration of the loop is completed. As a result, I am getting incomplete data. I understand what the problem is, but I don't understand the solution

const dbResult = await db.query("SELECT * FROM docs where id = 17");//17 is for example
    const doc = dbResult.rows[0];
    doc.linked.forEach(linked => {
      linked.assignedDocs = [];
      linked.links.forEach(async link => {
        const dbRes = await db.query("SELECT name, img FROM docs WHERE id = $1", [link.refId])
        link.assignedDocs.push({
          id: link.refId,
          name: dbRes.rows[0].name,
          img: dbRes.rows[0].img,
        })
      })
    });
    res.send(doc);

CodePudding user response:

forEach doesn't wait for async/await, use for ... of with async blocks

for (const linked of doc.linked) {
    // ...
    const dbRes = await func();
}
  • Related