【问题标题】:how can i get the value of a variable outside the arrow function in mern stack如何获取mern堆栈中箭头函数之外的变量值
【发布时间】:2022-02-07 19:15:03
【问题描述】:

我想在函数外获取这个变量的值const custDetail = await registeredUser.findOne(req.params);

const dashboardReq = async (req, res, next) => {
      try {
        const regCust = await registeredUser.findOne({ mobile: req.params.mobile });

    if (regCust == null) {
      console.log("No user found");
    } else {
      const custDetail = await registeredUser.findOne(req.params);
    }
    res.status(201).json({
      status: "success",
      data: { regCust },
    });
  } catch (error) {
    res.status(400).json({
      status: "fail",
      data: next(error),
    });
  }
};

【问题讨论】:

  • 你必须在设置它的值之前全局声明它。外部:let custDetail 然后删除内部的const

标签: javascript node.js mongodb express mern


【解决方案1】:

编辑使用res.locals将数据传递给另一个函数的简单方法

路由器:

router.get('getDashboardRef/:mobile', userCtl.dashboardReq, userCtl.nextFunction)

dashboardReq

const dashboardReq = async (req, res, next) => {
      try {
        res.locals.regCust = await registeredUser.findOne({ mobile: req.params.mobile });

    if (!res.locals.regCust) {
      console.log("No user found");
      throw new Error("No user found")
    } else {
      res.locals.custDetail = await registeredUser.findOne(req.params);
     next()
    }
  } catch (error) {
    res.status(400).json({
      status: "fail",
      data: error,
    });
  }
};

下一个函数

const nextFunction = (req, res) => {
  //do stuff with res.locals.custDetail
 res.status(201).json({
      status: "success",
      data: { res.locals.regCust },
    });
}

【讨论】:

  • 这里检查我数据库中的用户,如果他找到了,那么我想将用户的详细信息传递给其他函数
  • 你应该在其他函数中解析http请求,或者将此函数用作中间件并调用next。您可以发布您接下来要调用的功能吗?是预期的流程:查找用户>>查找用户详细信息>>将详细信息传递给其他功能>>对详细信息进行操作>>响应http请求?
  • 请检查我的编辑
  • 代码中的userctrl1和2是什么
  • 我假设您的路线看起来像这样,请发布您的路线和您接下来要调用的功能,这样我们可以更清楚地回答
【解决方案2】:

尝试重新审视您的设计,因为变量 custDetail 需要存在于路径本身内

如果这应该被记忆,那么维护一个地图,其中包含来自 req.params 的一些唯一标识符以及来自 registerUser.findOne 的结果

【讨论】:

    猜你喜欢
    • 2021-02-15
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多