简体   繁体   中英

JS await not working as expected with pg query

I want to use the return of a query to a postgresSQL database. I don't want to just print it. I want to use it in another function. The problem is that the function here returns before it is finished with executing the code.

async function create_base_config(user_id, service_id, timer_seconds) {
    var ret
    var line
    await db_adm_conn.query(`
    INSERT INTO base_config (user_id, service_id, timer_seconds)
    VALUES ('` + user_id + "', '" + service_id + "', '" + timer_seconds + "') RETURNING id;", (err, result) => {
        if (err) {
            ret = false
            line = err
            console.log("line2 err : " + line)

        }
        else {
            ret = true
            line = result.rows
            console.log("line2 : " + line)
            // json_return = JSON.parse(result)
            // console.log(result.rows)

        }
    });
    console.log("line: " + line)
    return { ret_value: ret, line_value: line };
}

To test it i inserted debug prints. The output is:

server_1   | line: undefined
server_1   | line2 : [object Object]
 

so I am exectuting the code after the await before the await is finished. How can i fix that, so that he first executes all the code from the await and then the rest?

you should not use a callback function as the arrow function. You should use try catch like this:

async function create_base_config(user_id, service_id, timer_seconds) {
    var ret
    var line
    try {
        line = await db_adm_conn.query(`
    INSERT INTO base_config (user_id, service_id, timer_seconds)
    VALUES ('` + user_id + "', '" + service_id + "', '" + timer_seconds + "') RETURNING id;")
        ret = true
    }
    catch (err) {
        ret = false
        line = err
    }
    return { ret_value: ret, line_value: line };
}

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