【问题标题】:MEAN stack async call seems to be getting fired before a response is receivedMEAN 堆栈异步调用似乎在收到响应之前被触发
【发布时间】:2020-02-26 02:53:06
【问题描述】:

我正在从 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】:

    您将 observables 和 Promise 结合起来,如果您刚刚开始,这将使您难以掌握这些概念。

    我的建议是让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 写了一个 good article 来解释为什么 async/await 让 Promise 更容易使用。

    【讨论】:

    • 这是有道理的,但现在它告诉我 authService 未定义
    • 您是否在组件的构造函数中注入了身份验证服务?您是否还在您的应用程序/功能模块中包含该服务?您问题中的代码没有显示这一点。
    • 是的。它在同一组件中的函数外部工作,但不在函数内部
    • 嗯,你为什么要这样嵌套函数?只需在组件级别将其分解为自己的功能即可。我写了另一个Stackoverflow answer,它谈到了为什么this 有时会很棘手,因为它的值取决于函数的调用方式(运行时绑定)。见developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2014-10-07
    • 2020-10-21
    • 1970-01-01
    • 2018-04-05
    • 2013-05-06
    相关资源
    最近更新 更多