0
votes

I completed this tutorial on making a graphql-node backend server built on Prisma2 and GraphQL. The tutorial doesn't explain why it writes some Resolver functions async and some not.

I thought that the async was added to functions that interacted with the database, but you can see this resolver gets data from the database but doesn't use async. But in this resolver it does use async.

Can somebody please explain why there is this seemingly arbitrary usage of async? When and why I should use it? Thanks in advance.

1
general (howtographql) tutorial can contain some errors/shortcuts (and it is not for explaining details), always follow specific (prisma) tutorial/docs - use async in both placesxadm

1 Answers

1
votes

The first thing you should do is read up on Promises. Promises are a way in JavaScript to encapsulate computations that are still ongoing. This is usually the case when you talk to an external service like a database or the operating system. They have been replacing callback style APIs.

In GraphQL a resolver can either return a value or a Promise that resolves to a value. This means, you can freely choose returning a value or a Promise, but if you call a database function like Prisma, you will get a Promise back, so you are kind of forced to stay "in Promise land", as there is no way to turn a Promise into a value. You can only chain functions, that should be executed with the value "in the future" (with then).

The last concept to understand is async/await. These async syntax is an addition to JavaScript syntax, that makes working with Promises easier. With await, you can stop the execution of a function until a value in a Promise arrives. Now, this looks like you are turning a Promise back into a value, but in reality, you function implicitly returns a Promise. For the VM to know about this, you have to state, that a function might use async by adding the keyword await in front of the function.

So when do you use async for a resolver? You could do it all the time, and the code would be correct. But doing it, even when you don't need to (e.g. you are not talking to a service) might have some performance implications. So it's better to only do it, if you really want to use the await keyword somewhere. I hope this can get you started with the concepts above, there is really a lot to learn. Maybe just go with your intuition and TypeScript errors until you deeply understand what is going on.