简体   繁体   中英

NodeJS function won't wait for PostgreSQL db call even with await

I'm trying to recursively add entries to the database with each entry being dependent on the previous entry (The previous entries' ID will be the next entries child_id). This would be all nice and dandy but i can't get the async/await to work properly.

Route, (qb is the class instance from the next code block)

// add orgs to db
router.post('/api/v1/orgs/add', async (req: Request, res: Response) => {
    const { org_name, daughters } = req.body;

    if (!org_name) return res.status(400).json({ err: 'MISSING_NAME' });

    const result = await qb.processRequest(org_name, daughters);

    res.json(result);
});
async processRequest(name: string, daughters?: any) {
    if (daughters) {
        daughters.map(async daughter => {
            return await this.processRequest(daughter.org_name, daughter.daughters);
        });

    }
    await this.insertOrg(name, daughters)
}

protected insertOrg(name: string, children?: number[]) {
    const childParam = children ? `array[${children}]` : 'NULL';

    const query = ` INSERT INTO orgs 
                        (org_name, daughters)
                    VALUES 
                        ('${name}', ${childParam})
                    RETURNING id`;

    pool.query(query, (err, res) => {
        if (err) throw err;

        return res.rows[0].id;
    });
}

example POST body

{
    "org_name": "Paradise Island",
    "daughters": [
        {
            "org_name": "Banana tree",
            "daughters": [
                {
                    "org_name": "Yellow Banana"
                }
            ]
        }
    ]
}

My goal here is that the innermost org, which has no children, would be added to the database with it's children being NULL. This entries' ID would be returned to the parent function, which would map the returned id to the daughters array and would itself be added to the database including the child's id.

insertOrg doesn't return a Promise to be await ed. Write it so that it will return a Promise that can be awaited.

protected insertOrg(name: string, children ? : number[]) {
  return new Promise((resolve, reject) => {
    const childParam = children ? `array[${children}]` : 'NULL';

    const query = ` INSERT INTO orgs 
                    (org_name, daughters)
                    VALUES 
                    ('${name}', ${childParam})
                    RETURNING id`;

    pool.query(query, (err, res) => {
      if (err) return reject(err);
      resolve(res.rows[0].id);
    });
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM