Reputation: 3176
I am trying out NestJS for the first time.
The question is simple, when I DO NOT use async await in my controller, I am able to return the data without await as async/await is used in the repository class methods
@Get('/:id')
getMessage(@Param('id') id: string) {
const messageId = id;
// works just fine 👇
const message = this.messagesService.findOne(messageId);
return message;
}
But when I make use of NotFoundException from NEST to make sure if I found the data I am supposed to return, I am forced to use async/await because without it, it considers the message
to be always there. Which I am assuming is a Promise.
@Get('/:id')
async getMessage(@Param('id') id: string) {
const messageId = id;
// 👇 await
const message = await this.messagesService.findOne(messageId);
if (!message) {
throw new NotFoundException('Message with ID not found');
}
return message;
}
And if I do not use await, it does not throw an exception.
Upvotes: 1
Views: 5353
Reputation: 113866
The await
keyword returns a Promise. Therefore if you return a Promise you have satisfied the contract of returning a Promise.
I presume that Nest.js repository methods need to return a Promise. You have two choices. Either use the async
keyword or return a Promise. In the first example you have returned a Promise so that is why it works.
Note that you don't need to use async
if you don't want to. You can always go old school. This is what your first example would be like with the logic to check the message:
@Get('/:id')
getMessage(@Param('id') id: string) {
const messageId = id;
// works just fine 👇
const promise = this.messagesService.findOne(messageId).then((message) => {
if (!message) {
throw new NotFoundException('Message with ID not found');
}
else {
return message;
}
});
return promise;
}
Upvotes: 1
Reputation: 113
The answer to your question is in the architecture of nestjs/node itself. If you return a promise (your first case) it resolve it and then returns the value. To get more clear idea about this check jiripospisil on 3 Aug 2018 on this issue.
Upvotes: 0
Reputation: 124
We know that in JS, program runs synchronously and findOne is a webAPI provided by the browser. As it is a webapi it will first send the line
const message = this.messagesService.findOne(messageId);
to the api and will return that function again to stack once all the data is received. (Assuming you know how the event loop and api works in JS)
Upvotes: 0