如何将 .then() 的一部分解析为其他函数

How to parse part of .then() as a other function

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

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 请求中的函数?

创建一个接收数据作为参数的处理程序和returns转换后的数据

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