How to Use Async Resolver in GraphQL: Simple Guide
In GraphQL, you use an
async function as a resolver to handle asynchronous operations like database calls or API requests. Simply declare the resolver function with async and use await inside it to wait for promises to resolve before returning data.Syntax
An async resolver in GraphQL is a function declared with the async keyword. It receives parameters like parent, args, context, and info. Inside, you use await to pause execution until a promise resolves, then return the result.
- async function: Marks the resolver as asynchronous.
- parent: The result from the parent resolver.
- args: Arguments passed in the GraphQL query.
- context: Shared data like authentication info.
- info: Query execution details.
javascript
const resolvers = { Query: { async getUser(parent, args, context, info) { const user = await fetchUserFromDB(args.id); return user; } } };
Example
This example shows a simple GraphQL server with an async resolver that fetches user data from a simulated database asynchronously.
javascript
const { ApolloServer, gql } = require('apollo-server'); // Sample type definitions const typeDefs = gql` type User { id: ID! name: String! } type Query { getUser(id: ID!): User } `; // Simulated async database fetch function fetchUserFromDB(id) { return new Promise((resolve) => { setTimeout(() => { resolve({ id, name: 'Alice' }); }, 100); }); } // Async resolver const resolvers = { Query: { async getUser(parent, args) { const user = await fetchUserFromDB(args.id); return user; } } }; // Create server const server = new ApolloServer({ typeDefs, resolvers }); // Start server server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
Output
Server ready at http://localhost:4000/
Common Pitfalls
Common mistakes when using async resolvers include forgetting to use async keyword, not using await for promises, or returning unresolved promises which causes unexpected results. Also, throwing errors inside async resolvers without proper handling can crash the server.
Always mark the resolver as async if you use await, and handle errors gracefully.
javascript
const resolvers = { Query: { // Wrong: missing async, returns a promise getUser(parent, args) { return fetchUserFromDB(args.id); // returns Promise, GraphQL handles but no await }, // Right: async with await async getUserAsync(parent, args) { const user = await fetchUserFromDB(args.id); return user; } } };
Quick Reference
- Declare resolver functions with
asyncto useawait. - Use
awaitto wait for asynchronous data fetching. - Return the resolved data, not the promise.
- Handle errors inside async resolvers to avoid server crashes.
- Async resolvers improve readability and maintainability of data fetching logic.
Key Takeaways
Always declare resolvers as async when using await inside them.
Use await to pause execution until asynchronous data is ready.
Return the actual data, not a promise, from your resolver.
Handle errors inside async resolvers to keep your server stable.
Async resolvers make your GraphQL code cleaner and easier to read.