Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

I've got a part of code which repeats few times in my code: The 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
};

How can I extract the part I've marked and use it as a function in other API requests?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Create a handler which receives the data as parameter and returns the transformed data

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 => {...});
}

And if this code is always called in the context of an express handler, you can even pass res to the dataHandler and if you are always returning the same error, you could also create an standard 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));
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!