Считается, что стек MEAN asyn c срабатывает до получения ответа - PullRequest
0 голосов
/ 25 февраля 2020

Я отправляю запрос на сервер node.js из приложения Angular и мне нужно дождаться ответа от сервера, прежде чем продолжить. Кажется, что-то не так с моим вызовом asyn c, но я не могу понять, что это такое.

Это мой компонент входа:

  onLogin() {
    if (this.form.invalid) {
      console.log(this.form);
      console.log('Form invalid');
      return;
    }
    this.isLoading = true;
    const findUserType = () => {
      return new Promise(resolve => {
        resolve(this.authService.getUserType(this.form.value.username));
      });
    };
    async function asyncCall() {
      console.log('getting user type');
      const result = await findUserType().then(userType => {
        console.log(userType);
      });
    }

Выполнение запроса через authservice:

  getUserType(username: string) {
    this.http.post<{ message: string; }>(
      'http://localhost:3000/api/user/find-user',
      { username }
    )
    .subscribe(response => {
      console.log(response.message);
      return response.message;
    });
  }

, который получает данные из nodejs:

router.post('/find-user', (req, res, next) => {
  function checkHauler() {HaulerUser.countDocuments({ username: req.body.username }, function (err, count) {
      if (count > 0) {
        return res.status(200).json({
          message: 'isHauler'
        })
      }
    });
  }
  function checkAbf() {AbfUser.countDocuments({ username: req.body.username }, function (err, count) {
      if (count > 0) {
        return res.status(200).json({
          message: 'isAbf'
        })
      }
    });
  }
  function checkUtility() {UtilityUser.countDocuments({ username: req.body.username }, function (err, count) {
      if (count > 0) {
        return res.status(200).json({
          message: 'isUtility'
        })
      }
    });
  }
  Promise.all([checkHauler(), checkAbf(), checkUtility()])
    .then(() => {
      console.log('done')
  })

Это то, что отображается в моей консоли:

getting user type
undefined
result: undefined

Uncaught TypeError: Cannot read property 'type' of undefined
    at setFieldValue (onloadwff.js:71)
    at HTMLFormElement.formKeydownListener (onloadwff.js:71)

isAbf

I ' Я очень новичок во всем этом, и любая помощь будет оценена !!

1 Ответ

0 голосов
/ 25 февраля 2020

Вы комбинируете наблюдаемые и обещания, которые сделают концепции намного более сложными, чем гр asp, если вы только начинаете.

Моя рекомендация: getUserType вернуть обещание, например:

  getUserType(username: string) {
    return this.http.post(
      'http://localhost:3000/api/user/find-user',
      { username }
    ).toPromise();
  }

Затем в другой функции вы можете записать результаты этого запроса POST:

    async yourAsyncCall() {
      console.log('getting user type');
      const result = await this.authService.getUserType('blahh insert test username here');
      console.log('post api result', result);
    }

Обратите внимание, что я исключил использование .then в пользу async / await. Hackernoon написал хорошую статью о том, почему async / await делает обещания намного проще в работе.

...