I'm bit new to NodeJs & NestJs. I always wondered what's the difference between using async as the method return type inside a controller vs executing async operation inside a regular method ? How does NodeJs handles the request in both these cases if there is huge traffic on this API (eg. 40K req/min). Will it be blocking in the 2nd example and non blocking in the 1st or would it work in a similar way?
For Eg:
@Controller('cats')
export class CatsController {
constructor(private catsService: CatsService) {}
@Post()
async sample() {
return "1234";
}
}
vs
@Controller('cats')
export class CatsController {
constructor(private catsService: CatsService) {}
@Post()
function sample() {
return await methodX();
}
async function methodX(){
return "1234"
}
Please ignore what the content in sample() & methodX() does its only for example.
First, marking a method as async enables you to use the await keyword inside of it.
For example in the second sample you provided, you need to mark the method sample as async to await methodX:
@Post()
async function sample() {
// Now `await` can be used inside `sample`
return await methodX();
}
So to answer your questions
what's the difference between using async as the method return type inside a controller vs executing async operation inside a regular method ?
There is none. In both cases, the method of the controller will need to marked as async. Performing what the route is supposed to perform in the body of the method or extracting it in another async method is just a matter of code organisation.
Will it be blocking in the 2nd example and non blocking in the 1st or would it work in a similar way?
Both examples would work in a similar way.
Second, marking a mehthod as async doesn't actually make it async if there is no real async operation performed in its body like a request to another service or a setTimeout. It means that the following samples
// Sample 1
@Post()
async sample() {
return "1234";
}
// Sample 2
@Post()
function async sample() {
return await methodX();
}
async function methodX(){
return "1234"
}
Are both equivalent to the synchronous method
@Post()
syncSample() {
return "1234";
}
Finally, as stated by @Micael Levi, return await is syntactically correct but should be avoided. Considering this sample:
@Post()
function async sample() {
return await methodX();
}
async function methodX(){
throw new Error('something failed')
}
Because the method sample return await methodX, sample won't appear in the stack trace which makes debugging more difficult.
We would prefer this sample:
@Post()
function async sample() {
const result = await methodX();
return result;
}
async function methodX(){
throw new Error('something failed')
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With