首页 > 解决方案 > ExpressJS - 返回未定义的函数

问题描述

函数checkFamilyStatus()由于某种原因一直返回 undefined,当它应该从 mongodb 集合返回一个布尔值时。

这里有一点上下文 - 我决定将逻辑部分与 get 和 post 方法等路由器方法分开,以使其看起来像函数式编程一样清晰易懂。所以我把逻辑部分放在函数中,并在路由器方法中调用它们,但是没有成功。此外,我不知道这是否是一个好习惯。如果这样做不是更容易阅读,而不是说,将一大堆代码放在一个地方吗?

我已经被这段代码卡住了一段时间。我对整个异步 JS 的工作感到有些困惑。我做了一些研究,但仍然不明白为什么这不起作用。有人可以为我澄清一下吗?

// post method 
router.post("/create", ensureAuthenticated, async(req, res) => {
      let userID = req.user.id;
      console.log(await checkFamilyStatus(userID)); // but returns undefined
      // rest of the code
    }



    // check family status
    checkFamilyStatus = async userID => {
      Account.findOne({
        _id: userID
      }, (err, account) => {
        return account.hasFamily; // should return boolean value ?
      });
    };

标签: node.jsexpressasynchronousmongooseasync-await

解决方案


假设背后的逻辑account.hasFamily是正确的,那么你需要await为返回,所以它应该是return await account.hasFamily;


推荐阅读