【问题标题】:how to make one function instead of 3 functions?如何制作一个功能而不是三个功能?
【发布时间】:2020-10-31 22:47:46
【问题描述】:

我注意到唯一改变的是三个函数中的Product.find({type:''}),所以它们都一样...

我可以做一个功能做同样的工作吗?

routes.js 文件:

    mainRouter.get('/showChips',showChips);
    
    mainRouter.get('/showJuices',showJuices);
    
    mainRouter.get('/showSoftDrinks',showSoftDrinks);

controller.js 文件:

const showChips = async (req,res)=>{
    const chipsItems = await Product.find({type:'chips'});
    console.log(chipsItems);
    res.json(chipsItems)

};

const showJuices = async (req,res)=>{
    const juicesItems = await Product.find({type:'juices'});
    console.log(juicesItems);
    res.json(juicesItems)
};

const showSoftDrinks = async (req,res)=>{
    const softDrinksItems = await Product.find({type:'Soft Drinks'});
    console.log(softDrinksItems);
    res.json(softDrinksItems)
};

【问题讨论】:

    标签: javascript node.js mongodb mongoose routes


    【解决方案1】:

    您可以创建一个返回 .finds 特定类型的函数的高阶函数:

    const makeShowProduct = type => (req, res) => {
      Product.find({ type })
        .then(result => res.json(result))
        .catch(handleErrors); // don't forget this part - don't create unhandled rejections
    };
    
    router
      .get('/showChips', makeShowProduct('chips'))
      .get('/showJuices', makeShowProduct('juices'))
      .get('/showSoftDrinks', makeShowProduct('Soft Drinks'))
    

    【讨论】:

    • 这是为什么呢?未定义handleErrors
    • 它的实现取决于你,但你需要在.catch 中添加 something - 不推荐使用未处理的拒绝,这将导致 Node 在新版本中退出。弄清楚如果遇到错误你想做什么,并在函数中实现它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    相关资源
    最近更新 更多