How to use Knexjs synchronously on Apollo GraphQL Server

Viewed 341

How can I use Knexjs to fetch data synchronously on a resolver in Apollo GraphQL Server? For instance, if I run the following query:

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')
        }
    }
}

The line console.log(result); just displays a Promise {<pending>} and by the time the line .then(function(rows) {console.log(rows)}) is executed (asynchronously), the main function will be already finished.

Is there a way to get the result of the database query instead of a Promise on line console.log(result);?

1 Answers

If you want your request to run synchronously and wait the result you need to add 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)
}

As you noticed, I removed the .then and the .catch that are not relevant anylonger.

I highly recommend adding a try/catch around your awaited promise to avoid 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
    }
}

By the way, the return db.knex.select('*').from('SomeOtherTable') would benefit an await aswell to return data instead of a promise.

Related