MEAN堆栈异步调用似乎在收到响应之前被触发

问题描述 投票:0回答:1

我正在从Angular应用程序向node.js服务器发出请求,需要等到服务器收到响应后再继续。我的异步呼叫似乎出了点问题,但我不知道这是什么。

这是我的登录组件:

  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

我对所有这些都非常陌生,将不胜感激!

node.js angular mean-stack
1个回答
0
投票

[您将可观察性和承诺结合在一起,如果您刚开始,这将使这些概念变得更加难以掌握。

我的建议是让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的使用以支持异步/等待。 Hackernoon写了一篇good article,说明了为何异步/等待使承诺变得如此容易使用。

© www.soinside.com 2019 - 2024. All rights reserved.