我怎样才能在mern堆栈中获取箭头函数外的变量值

how can i get the value of a variable outside the arrow function in mern stack

我想在函数外获取这个变量的值 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),
    });
  }
};

Edit 使用 res.locals

将数据传递给另一个函数的简单方法

路由器:

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

仪表板请求

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 },
    });
}

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

如果这应该被记忆,然后维护一个映射,其中包含来自 req.params 的一些唯一标识符以及来自 registeredUser.findOne

的结果