Why aren't resolvers in Query async/await?

In Lift-off part 4, for mutations, the tutorial says to make the resolvers async functions because we’re awaiting the call to the rest API (which makes sense), but then why don’t we need to mark resolvers in Query as async if they could be getting data from the restAPI?

Hi @latc!

Great question! We did gloss over this to avoid adding too much new/overwhelming information. To answer your question, there are actually multiple possible return types for a resolver in Apollo Server. They’re all outlined on this page of our documentation.

In the courses so far we’ve always returned the last type: a Promise.

Resolvers often perform asynchronous actions, such as fetching from a database or back-end API. To support this, a resolver can return a promise that resolves to any other supported return type.

In Lift-off I to III, our TrackAPI calls returned promises that then resolve to either arrays (tracksForHome) or objects (track, module). We didn’t need to make the resolver async explicitly because ApolloServer allows having a Promise as a return value.

We could add explicit async/awaits in those resolvers and it would still work!

In Lift-off IV, for the incrementTrackViews resolver, we wanted to wait for the promise to either finish or throw an error. So we needed to add an await in front of it. We can’t use await without making the parent function async, so we had to add that as well. This resolver returns an object based on the results of that promise.

I hope that makes sense, feel free to ask any follow-up questions!

1 Like