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



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

我强烈建议在您等待的承诺周围添加一个try/catch,以避免未捕获的错误。

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')返回数据而不是承诺将有利于等待。