首页 > 解决方案 > 链接函数不能同步工作

问题描述

我查询数据库如下:

const testMe = async () => {
    const index = await _fetchNextIndex()

    if (index === undefined) {
        throw new Error('Next index could not fetched')
    }

    return 'Success'
}


const _fetchNextIndex = async () => {
    return db.query("SELECT nextval(pg_get_serial_sequence('testme_table', 'id'))", (err, result) => {
        if (err) {
            throw new Error('Index could not generated')
        }
        return result.rows[0]
    })
}

db定义为:

const {Pool} = require('pg')
const pool = new Pool()

module.exports = {
    query: async (text, params, callback) => {
        return await pool.query(text, params, callback)
    }
}

我的代码不能同步工作。index未定义并引发错误。但是,当我调试应用程序时,我看到该行在一段时间后被调用:

return result.rows[0]

我想念什么?

编辑1:我已经添加asyncawait进入query功能。

编辑 2:我还删除了回调。

const {Pool} = require('pg')
const pool = new Pool()

module.exports = {
    query: async (text, params) => {
        return await pool.query(text, params)
    }
}

标签: javascriptnode.jsasynchronousasync-awaitnode-postgres

解决方案


推荐阅读