【问题标题】:How to parse part of .then() as a other function如何将 .then() 的一部分解析为其他函数
【发布时间】:2022-01-22 21:30:08
【问题描述】:

我有一段代码在我的代码中重复了几次:函数:

exports.getCategoryProducts = (req, res) => {
db.collection("products")
    .where("category", "==", req.params.category)
    .limit(10)
    .get()
    //duplicate code starts
    .then((data) => {
        let products = [];
        data.forEach((doc) => {
            products.push({
                id: doc.id,
                title: doc.data().title,
                category: doc.data().category,
                description: doc.data().description,
                image: doc.data().image,
                price: doc.data().price,
                rating: doc.data().rating,
            });
        });
        return res.status(200).json(products);
    })
    .catch((err) => {
        console.log(err);
        return res.status(500).json({
            message: "Something went wrong, please try again later",
        });
    });
    //duplicate code ends
};

如何提取我标记的部分并将其用作其他 API 请求中的函数?

【问题讨论】:

  • 您可以创建一个回调函数cb 来获取数据并在.then 中执行所有操作。类似的错误。然后将其与.then(cb).catch(cbErr) 一起使用
  • 一个.forEach() 总是.push()es 数组中的东西应该是一个.map()

标签: javascript node.js promise


【解决方案1】:

创建一个处理程序,接收数据作为参数并返回转换后的数据

function dataHandler(data) {
  return data.map(doc => ({
            id: doc.id,
            title: doc.data().title,
            category: doc.data().category,
            description: doc.data().description,
            image: doc.data().image,
            price: doc.data().price,
            rating: doc.data().rating,
  }));
}


function getCategoryProducts((req, res) => {
  db.collection("products")
    .where("category", "==", req.params.category)
    .limit(10)
    .get()
    .then(data => dataHandler(data))
    .then(products => {
      res.status(200).json(products);
    })
    .catch(e => {...});
}

如果此代码始终在快速处理程序的上下文中调用,您甚至可以将res 传递给dataHandler,如果您总是返回相同的错误,您还可以创建一个标准的errorHandler

function dataHandler(data, res) {
  res.status(200).json(data.map(doc => {
       let dd = doc.data();
       return {
            id: doc.id,
            title: dd.title,
            category: dd.category,
            description: dd.description,
            image: dd.image,
            price: dd.price,
            rating: dd.rating,
       }
     }));
}

function errorHandler(err, res) {
  console.log(err);
    res.status(500).json({
        message: "Something went wrong, please try again later",
    });
}

function getCategoryProducts((req, res) => {
  db.collection("products")
    .where("category", "==", req.params.category)
    .limit(10)
    .get()
    .then(data => dataHandler(data, res))
    .catch(e => errorHandler(e, res));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    • 2012-09-14
    • 2020-05-16
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多