1

I am trying to return a particular response when a data is inserted in postgresql. The query works perfectly, Inserts data into DB but before returning a response it prints undefined. Kindly check the code below.

async function signUp(info) {
    const {
        firstName,
        lastName,
        address,
        email,
        phoneNumber,
        password,
        city,
        postal_code,
    } = info;

    console.log("only info: ", phoneNumber);

    const queryInsertNewUser = `INSERT INTO public."Users"(
        "First_Name", "Email", "Mobile", "Address", "User_Type", "Last_Name", "password", "city","postal_code")
        VALUES ('${firstName}', '${email}', '${phoneNumber}', '${address}', 'Customer', '${lastName}', '${password}','${city}','${postal_code}')
        RETURNING user_id;`;



    client.query(queryInsertNewUser, (err, result) => {
        if (!err) {
            if (result.rowCount == 1) {
                console.log("User registered.");
                return {
                    status: "Success",
                    msg: "User Registered Successfully",
                    user_id: result.rows[0].user_id,
                };
            } else {
                console.log("Not Registered.");
                return {
                    status: "Error",
                    msg: "Could not register user. Call Developer.",
                };
            }
        } else {
            console.log(err);
        }
    });
}


app.post("/signup", async(req, res) => {
    const { email } = req.body;
    const data = await signUp(req.body);
    console.log(data);
});

I tried shortening the code, tried async/await still does not work. If I remove the client.query part of signUp method and replace it with return " hello". the Console.log prints hello.

  • Hi, please be more specific while writing the questions like, where do you get `undefined` like for which console log or is it internally printed by the query client and which client are you using for query execution, provide supporting information to help others help you. – Rohit Ambre Jan 10 '23 at 19:37
  • @RohitAmbre I am getting undefined printed in the "/signup" api. When I hit the api "/signup" this line "const data = await signUp(req.body);" is executed. The next line that is "console.log(data);" is printing undefined – Excellent Technologies BD Jan 10 '23 at 20:06
  • Did you try printing the `result` before 1st `if` condition – Rohit Ambre Jan 11 '23 at 07:06
  • @RohitAmbre Yes, I did. Everything is working inside the client.query. I am assuming it also returns the JSON object. But while it's being returned, the "console.log(data)" line gets executed before getting the JSON object into the data variable. – Excellent Technologies BD Jan 12 '23 at 07:28
  • not sure what is going wrong here, as you said, data is getting inserted in the table and you also tried to convert this into Promise/Async-await, and it is also not throwing any error. I'll post one code try that. – Rohit Ambre Jan 12 '23 at 08:52

1 Answers1

0

Try below code, see if it helps.

async function signUp(info) {
    try {
        const {
            firstName,
            lastName,
            address,
            email,
            phoneNumber,
            password,
            city,
            postal_code,
        } = info;
    
        console.log("only info: ", phoneNumber);
    
        const queryInsertNewUser = `INSERT INTO public.Users(
    First_Name, Email, Mobile, Address, User_Type, Last_Name, password, city,postal_code)
    VALUES ($1, $2, $3, $4, 'Customer', $5, $6, $7, $8)
    RETURNING user_id;`;
    
        const params = [firstName, email, phoneNumber, address, lastName, password, city, postal_code]
    
        const result = await client.query(queryInsertNewUser, params);
        console.log("Result here", result)
        if (result) { // OR (result && result.rowCount)
            return {
                status: "Success",
                msg: "User Registered Successfully",
                user_id: result.rows[0].user_id,
            }
        }
        console.log("Not Registered.");
        return {
            status: "Error",
            msg: "Could not register user. Call Developer.",
        }
    } catch (error) {
        console.error("Error", error)
        return {
            status: false
        }
    }
}

If you want to use callback for query then try changing it like below, but I'll suggest to move it to Promise

client.query(queryInsertNewUser, (err, result) => {
    if (err) {
        console.log(err);
        return {
            status: false
        }
    }
    if (result && result.rowCount) {
        console.log("User registered.");
        return {
            status: "Success",
            msg: "User Registered Successfully",
            user_id: result.rows[0].user_id,
        };
    } else {
        console.log("Not Registered.");
        return {
            status: "Error",
            msg: "Could not register user. Call Developer.",
        };
    }
});
Rohit Ambre
  • 921
  • 1
  • 11
  • 25