【问题标题】:How to use multiple functions in an api route?如何在一个 api 路由中使用多个函数?
【发布时间】:2019-08-22 21:32:45
【问题描述】:

我正在尝试使用此 Api GET Route 来查找经过身份验证的用户团队中的所有玩家。我觉得 const 变量是正确的,但我不确定我正在做的事情是否可能在 .then() 中使用异步函数,以便我可以使用同步等待但是我收到 findTeam 未定义

路由中使用的身份验证是我的 jwt 中间件,它允许我使用 req.user.id 中间件来获取经过身份验证的用户 ID。

router.get('/Team', auth, async function(req, res) {
  //get USers team
  const findTeam = await TeamUsers.findOne({
    where: {
      UserID: req.user.id
    }
  })
    .then(findTeam, async function(req, res) {
      const findTeamID = findTeam.TeamID;

      const findUsers = await TeamUsers.findAll({
        // get the players teamUSers get that Id then
        where: {
          TeamID: findTeamID
        }
      });
    })
    .then(findUsers, async function(req, res) {
      const findUsers = await Users.findByPk(findUsers.id);

      console.log(findUsers.first_name);
      res.status(200).json(findUsers);
    })

    .catch(err => {
      res.status(400).send('unable to save to database');
    });
});

【问题讨论】:

  • Promise.then (success, failure) 然后采用两个函数,第一个用于成功回调,第二个用于失败回调函数,因此如果您需要使用,则必须将下一个异步函数传递给 first参数和传递数据参数不是 req,res

标签: node.js api sequelize.js


【解决方案1】:

那就不用了

你可以在没有 then 的情况下编写所有代码,它将同步运行 但是您必须通过检查参考来检查函数返回的值是否未引发异常

const findTeam = await TeamUsers.findOne({
                            where: {
                                UserID: req.user.id
                            }
                        });

if(findTeam){

    const findTeamID = findTeam.TeamID;    
    const findUsers = await TeamUsers.findAll({
                // get the players teamUSers get that Id then
                                where: {
                                    TeamID: findTeamID
                                }
                            });

    if (findUsers) { ...etc } 

} 

您可以通过 try catch 块或带有 catch 回调的链函数来捕获异常

【讨论】:

    猜你喜欢
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    相关资源
    最近更新 更多