链式async函数未同步执行,await获取数据库查询结果为undefined
问题原因
你混用了回调和async/await两种异步处理模式,导致返回值不符合预期:
- node-postgres的
query方法支持两种调用规则:传入回调时走回调逻辑,返回值为undefined;不传回调时才会返回Promise,可被await调用。你最初的_fetchNextIndex给db.query传入了回调函数,所以db.query返回值为undefined,await之后拿到的index自然是undefined。而回调内部的return仅作用于回调函数本身,无法将结果返回给外层的_fetchNextIndex,所以你会看到这行返回逻辑晚于index判断逻辑执行。 - 你修改
db.query去掉回调参数之后,需要同步调整_fetchNextIndex的写法,移除回调参数,改用try/catch捕获异步错误。
修改后的代码示例
const _fetchNextIndex = async () => { try { const result = await db.query("SELECT nextval(pg_get_serial_sequence('testme_table', 'id'))") return result.rows[0] } catch (err) { throw new Error('Index could not generated') } }
修改后testMe中await _fetchNextIndex()就可以正确拿到返回的index值,不会再出现提前抛出undefined错误的问题。
内容的提问来源于stack exchange,提问作者kamaci
相关产品推荐
相关产品推荐

