作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何使用 Knexjs在 Apollo GraphQL Server 中的解析器上同步获取数据?例如,如果我运行以下查询:
const resolvers = {
Query: {
MySchema: (_, args, { dataSources }, info) => {
var result = db.knex.select('*')
.from('SomeTable')
.where({SomeColumn:'SomeValue'})
.then(function(rows) {console.log(rows)})
.catch(function(error) {console.error(error)});
// Do something with the result here..
console.log(result);
return db.knex.select('*').from('SomeOtherTable')
}
}
}
行console.log(result);
只显示 Promise {<pending>}
到时候 .then(function(rows) {console.log(rows)})
被执行(异步),主函数将已经完成。
有没有办法获取数据库查询的结果而不是行 console.log(result);
上的 Promise? ?
最佳答案
如果你希望你的请求同步运行并等待你需要添加async/await的结果
MySchema: async (_, args, { dataSources }, info) => {
var result = await db.knex.select('*')
.from('SomeTable')
.where({SomeColumn:'SomeValue'})
// result is now a value and not a promise
console.log(result)
}
如您所见,我删除了不再相关的 .then 和 .catch。
我强烈建议在您等待的 promise 周围添加一个 try/catch 以避免 Uncaught Error 。
MySchema: async (_, args, { dataSources }, info) => {
try {
var result = await db.knex.select('*')
.from('SomeTable')
.where({SomeColumn:'SomeValue'})
// result is now a value and not a promise
console.log(result)
} catch (e) {
// handle e
}
}
顺便说一句,return db.knex.select('*').from('SomeOtherTable')
也会让 await 受益,以返回数据而不是 promise 。
关于apollo-server - 如何在 Apollo GraphQL Server 上同步使用 Knexjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63385708/
我是一名优秀的程序员,十分优秀!