gpt4 book ai didi

apollo-server - 如何在 Apollo GraphQL Server 上同步使用 Knexjs

转载 作者:行者123 更新时间:2023-12-05 04:59:44 24 4
gpt4 key购买 nike

如何使用 KnexjsApollo 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com