Почему не получается вернуть текст из контроллера?

Описал контролер:
@Get('/checkEmailForBusy/:email')
checkEmail( @Param('email') email ) {
    return this.userService.CheckEmailForBusy(email);
}

Также описал сервис:
async CheckEmailForBusy(email: any) {
        try {
            this.UserRepository.count({
                 where: {email: email.toString()}
            }).then( (Res) => {
                if (Res > 0) {
                    return '{"status": "200","Message": "This email is busy"}';
                }
                else {
                    return '{"status": "200", "Message": "kk"}';
                }
            })
        } catch (err) {
            console.log(err);
            return `{"text": "${err}"}`;
        }
    }

Если поставить console.log() в этот сервис, он отработает, но текст не возвращается.
Для тех кому интересно, более полный код:
Сервис:
@Injectable()
export class UserService {
constructor(@InjectModel(User) private UserRepository: typeof User ) {}
...
async CheckEmailForBusy(email: any) {
        try {
            this.UserRepository.count({
                 where: {email: email.toString()}
            }).then( (Res) => {
                if (Res > 0) {
                    return '{"status": "200","Message": "This email is busy"}';
                }
                else {
                    return '{"status": "200", "Message": "kk"}';
                }
            })
        } catch (err) {
            console.log(err);
            return `{"text": "${err}"}`;
        }
    }

контроллер:
@Controller('user')
export class UserController {

    constructor(private userService: UserService) {}
...
@Get('/checkEmailForBusy/:email')
    checkEmail( @Param('email') email ) {
        return this.userService.CheckEmailForBusy(email);
    }
  • Вопрос задан
  • 45 просмотров
Решения вопроса 1
@StiflerProger
Потому-что у тебя метод CheckEmailForBusy вернёт Promise void в случае, если он отработает без ошибок.

async CheckEmailForBusy(email: any) {
        try {
            const res = await this.UserRepository.count({
                 where: {email: email.toString()}
            });
            if (res > 0) {
                 return '{"status": "200","Message": "This email is busy"}';
            }
            else {
                 return '{"status": "200", "Message": "kk"}';
            }
        } catch (err) {
            console.log(err);
            return `{"text": "${err}"}`;
        }
    }


если хочешь использовать .then , нужно обернуть в Отдельный промис, и убрать async приставку

public CheckEmailForBusy(email: any) {
  return new Promise((res, rej) => {
    this.UserRepository.count({
      where: {email: email.toString()}
    }).then( (Res) => {
      if (Res > 0) {
        return res('{"status": "200","Message": "This email is busy"}');
      }
      else {
        return res('{"status": "200", "Message": "kk"}');
      }
    }).catch(err => {
       return rej(`{"text": "${err}"}`);
    })
  });
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы