执行signUp函数时出现未定义的情况。

huangapple go评论87阅读模式
英文:

Getting undefined when executing signUp function

问题

以下是您要翻译的代码部分:

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

请注意,由于JavaScript的异步性质,client.query的回调函数中的return语句不会直接返回值给signUp函数的调用者。您可能需要重构代码以处理回调函数的方式来处理异步操作,或者考虑使用await来等待client.query的结果。这是解决问题的一种方式。

英文:

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.

答案1

得分: 0

尝试以下代码,看看是否有帮助。

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
        }
    }
}

如果要使用回调进行查询,尝试将其更改如下,但我建议将其改为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.",
        };
    }
});
英文:

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.",
        };
    }
});

huangapple
  • 本文由 发表于 2023年1月11日 03:09:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75074734.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定