0

I'm testing async/await in typescript, i created example functions in my class, then i pass the function testarSemAsyncAwait for my route, when i tested in Postman shows this error:

enter image description here

I change the function several times, but i don't know what is the problem!

This is the code:

import { Router, Request, Response, NextFunction } from "express";

class UsuarioController {
  constructor() {}

  public fun1 () : any {
    setTimeout(function() {
      console.log('F1');
      return 4000;
    }, 4000);
  }

  public fun2 () : any {
    setTimeout(() => {
      console.log('F2');
      return 500;
    }, 500);
  }

  public async testarComAsyncAwait(req: Request, res: Response) {
    let x = await this.fun1();
    let y = await this.fun2();
    console.log('pronto');
  }

  public testarSemAsyncAwait(req: Request, res: Response) {
    let x = this.fun1();
    let y = this.fun2();
    console.log('pronto');
  }

}

const usuarioController = new UsuarioController();
export default usuarioController;

And this is the route:

import { Router }  from 'express';
import bcrypt = require('bcrypt');
import usuarioController from '../controllers/usuarioController';

class UsuarioRouter {
  router: Router;

  constructor() {
    this.router = Router();
    this.routes();

  }

  /**
   * Função que cria e define as rotas e suas respectivas funções no UserController
   */
  routes() {
    this.router.get('/', usuarioController.listUsuarios); // Rota para listar todos os usuários inseridos no BD
    this.router.post('/', usuarioController.createUsuario);  //  Rota para criar usuário e inserir no BD
    this.router.put('/:login', usuarioController.updateUsuario); //  Rota para atualizar dados do usuário no BD
    this.router.delete('/:login', usuarioController.deleteUsuario);  //  Rota para deletar usuário do BD
    this.router.post('/login', usuarioController.validateToken); //  Valida token do usuário no login
    this.router.post('/receberDados', usuarioController.receberDadosSQL); //  Rota para receber e tratar JSON do SQLServer
    this.router.get('/enviarDados', usuarioController.enviarDadosAPP); //  Rota que envia os dados solicitados pelo cliente (APP)
    this.router.get('/testeAsync', usuarioController.testarSemAsyncAwait); // Teste de Async/Wait
    //this.router.get('/teste/auth', usuarioController.testarToken); // Testa o uso de token em rotas -> funcionou
  }
}

//  Exportação
const usuarioRoutes = new UsuarioRouter();
usuarioRoutes.routes();
export default usuarioRoutes.router;

The route with the error is:

this.router.get('/testeAsync', usuarioController.testarSemAsyncAwait);

Any help is welcome!

0 Answers0