繁体   English   中英

无法在 Javascript 中调用函数

[英]Not able to call a function in Javascript

我在createProfile调用函数createOne并且createOne似乎没有被执行。 我正在尝试在数据库中创建一个用户。 该路线按预期工作,只是我无法在函数内调用函数。

请帮忙!

exports.createOne = Model =>
  catchAsync(async (req, res, next) => {
    console.log("I am in createone")

    const doc = await Model.create(req.body);


    res.status(201).json({
      status: 'success',
      data: {
        data: doc
      }
    });
  });
exports.createProfile = (req,res) => {
    console.log(req.query.segment);
    if(req.query.segment == "Tour"){
        let Segment = Tour;
        console.log(factory);
        factory.createOne(Tour);
    }

}

请在控制台日志的以下结果中找到该功能根本不会触发。

Tour
{ getOne: [Function], createOne: [Function] }
POST /api/v1/midasCommon/?segment=Tour - - ms - -

问题是,根据您给出的 catchAsync 定义,

const catchAsync = fn => { 
  return (req, res, next) => { 
    fn(req, res, next).catch(next);
  };
}; 

您正在返回一个从未被调用的带有 catchAsync 的函数。 你用factory.createOne(Tour);做什么factory.createOne(Tour); 只是调用 catchAsync,但您还需要再调用一次。

你可以做factory.createOne(Tour)(); 或将 createOne 更改为:

exports.createOne = Model =>
  catchAsync(async (req, res, next) => {
    console.log("I am in createone")

    const doc = await Model.create(req.body);


    res.status(201).json({
      status: 'success',
      data: {
        data: doc
      }
    });
  })(); // <-- Notice the call

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM