0

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);

1 Answer 1

1

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

for (const linked of doc.linked) {
    // ...
    const dbRes = await func();
}
Sign up to request clarification or add additional context in comments.

3 Comments

forEach if I give async callback work ok. I get all data by using const link = await dbRes.rows[0]; If it will not waiting, I`ll getting promise. In console log I can see how console log send execute before console log link.
seems like yes. I need top levels for of await. I have another one question, does it will work with recursive? So at some point I will need use recursive to get deeper docs. Does recursive calls will wait?
It would work with recursive calls. It depends how your code is designed.

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.