-1

I have this repository , it should get the message by id :

  findOne(id: number) {
    return readFile('messages.json', 'utf8', (err, file: string) => {
      const messages = JSON.parse(file);
      return messages[id];
    });
  }

this is the service :

  findOne(id: number) {
    return this.messagesRepo.findOne(id);
  }

and this is the controller

  @Get('/:id')
  getMessage(@Param() param: GetMessageDTO) {
    const message = this.messagesService.findOne(param.id);
    if (message == null) {
      throw new NotFoundException('message not found');
    }
    return message;
  }

I want the controller to wait for the execution of the function but I can't use async/await because readFile doesn't return promise , what should I do?

esraa
  • 146
  • 1
  • 15
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – derpirscher Jan 15 '23 at 17:00
  • 1
    Use promises api of fs module – Konrad Jan 15 '23 at 17:06

1 Answers1

1

instead of readFile from fs, you can use the one from promises API of FS module like so:

import { readFile } from 'fs/promises'
// ...
 async findOne(id: number): Promise<any> {
    const jsonFileTxtBuffer = await readFile('messages.json');
    const messages = JSON.parse(jsonFileTxtBuffer);
    return messages[id];
  }

Don't forget the await on calling .findOne(), of course.


pretty basic JS and node.js stuff not related with NestJS :)

Micael Levi
  • 5,054
  • 2
  • 16
  • 27