I am trying to write 2 routes for my node app.
1 route is to return single item and 1 route is for array list.
The routes are like these.
router
.route("/:income_id")
.get((req, res) => {
Income.findById(req.params.income_id)
.populate("services.service_id")
.then((income) => {
return filterIncomeFunc(income);
})
.then((result) => {
return res.status(200).json(result);
})
.catch(function (error) {
res.status(404).json({ msg: "Income not Found" });
});
});
router
.route("/")
.get((req, res) => {
Income.find({})
.populate("services.service_id")
.then((income) => {
//problem here
return filterArrayIncome(income);
})
.then((result) => {
console.log('======================');
console.log(result);
console.log('======================');
return res.status(200).json(result);
})
.catch(function (error) {
res.status(404).json({ msg: "Income not Found" });
});
});
Since I need to filter 2 of these i write 2 helper array named filterArrayIncome
& filterIncomeFunc
I code works for single item but the array function is not working,
Here are my code for filtering
const filterIncomeFunc = (income) => {
return new Promise((resolve, reject) => {
let filteredIncome = {};
filteredIncome.services = income.services.map((service) => {
return {
service_name: service.service_id.service_name,
price: service.price,
};
});
filteredIncome.total_amount = income.total_amount;
resolve(filteredIncome);
});
};
const filterArrayIncome = (incomeArray) => {
return new Promise((resolve, reject) => {
let filteredIncome = incomeArray.map((eachIncome) => {
return filterIncomeFunc(eachIncome);
});
resolve(filteredIncome);
});
};
Since i want dry code i am using filterIncomeFunc
inside the filterArrayIncome
Inside the filterArrayIncome the console.log result is like this.
======================
[
Promise {
{
services: [Array],
total_amount: 18000
}
},
Promise {
{
services: [Array],
total_amount: 18000
}
},
]
======================
Y these are returning promises. I already resolve inside the filterArrayIncome
func
question from:
https://stackoverflow.com/questions/65889739/how-to-resolve-these-promise-chaining 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…