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

How to use Knexjs synchronously on Apollo GraphQL Server

如何使用Knexjs to fetch data synchronously on a resolver in 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') 也有利于等待 return 数据而不是承诺。