ArthurJ
ArthurJ

Reputation: 849

Using Async/Await with array map to insert data into a postgres table

I am new to promises and unsure what I am missing from my code below as unfortunately my req.body jobGroups are not being inserted within my postgres table.

Within my index.js express code, I have the following. FYI, some sections of code have been left out.

The value of req.body is:

{
    "jobName": "ABC",
    "jobType": "1",
    "jobGroups": [
        {
            "jobGroupName": "A1",
        },
        {
            "jobGroupName": "B2",
        }       
    ]
}

When I call my route /process-job from my client, I see that the record is created within my my_jobs table but when it comes to processing the my_job_groups table, nothing is getting inserted.

I basically need to get both A1 and B2 created within the my_job_groups table using the job_id returned from the my_jobs insert.

Not sure if I am using my promises and async/await correctly?

const express = require("express");
const app = express();
const cors = require("cors");
const pool = require("./db");


app.post("/process-job", async (req, res) => {
  try {
    const { jobName, jobType } = req.body
    const jobDetails = req.body.jobGroups;

    const theJob = await pool.query(        
        "INSERT INTO my_jobs (job_name, job_type) VALUES($1, $2) RETURNING job_id", 
            [ jobName, jobType ]
    );
    let jobId = theJob.rows[0];

    try {
      const promises = jobDetails.map(async jobDetail => {       
        let newJob = await pool.query(        
          "INSERT INTO my_job_groups (job_id, job_group_name) VALUES($1, $2) RETURNING job_group_id", 
              [ jobId, jobDetails.jobGroupName ]
        );

        return {
          id: newJob.rows[0]
        }
      })

      const results = await Promise.all(promises)
    } catch(err) {
      console.error(err.messasge);
    }
  } catch(err) {
    console.error(err.messasge);
  }
})

Upvotes: 2

Views: 1555

Answers (2)

Vineet Pathar
Vineet Pathar

Reputation: 1

Use “pool.promise().query” insted of pool.query

It will make it promise forcefully so await will work with it

Upvotes: 0

hoangdv
hoangdv

Reputation: 16147

Just wrap all your code into one try/catch block is enough. When insert to my_job_groups, job_group_name should be jobDetail.jobGroupName instead of jobDetails.jobGroupName.

And, I think should be better if your API returns a response to the client.

const express = require("express");
const app = express();
const cors = require("cors");
const pool = require("./db");


app.post("/process-job", async (req, res) => {
  try {
    const { jobName, jobType, jobGroups: jobDetails } = req.body // destruct to get all properties

    const job = await pool.query(
      "INSERT INTO my_jobs (job_name, job_type) VALUES($1, $2) RETURNING job_id",
      [jobName, jobType],
    );
    const jobId = job.rows[0];

    const promises = jobDetails.map(async jobDetail => {
      const newJob = await pool.query(
        "INSERT INTO my_job_groups (job_id, job_group_name) VALUES($1, $2) RETURNING job_group_id",
        [jobId, jobDetail.jobGroupName] // jobDetail.jobGroupName instead of jobDetails.jobGroupName
      );

      return {
        id: newJob.rows[0],
      };
    });

    const result = await Promise.all(promises);

     res.json(result);
  } catch (err) {
    console.error(err); // print out message object
    res.status(500).json({ message: err.message }); // response with status 500
  }
});

Upvotes: 0

Related Questions