I am trying to get data from database using the callback method "getAllOrdersByUserId". The results of it are below:
[ TextRow {
DishOrderId: 163,
BagId: 'BPZDXT68148',
DateCreated: 2021-05-27T03:55:05.000Z,
Bags:
'[{"DishId":43,"DishName":"Kuchvi Biryani","Spicy":2,"UnitPrice":"6.99","Qty":5,"DishTotal":"34.95"}]',
},
TextRow {
DishOrderId: 162,
BagId: 'BNJENZ08608',
DateCreated: 2021-05-27T03:46:26.000Z,
Bags:
'[{"DishId":41,"DishName":"Dum Biryani","Spicy":2,"UnitPrice":"6.99","Qty":5,"DishTotal":"34.95"}, {"DishId":42,"DishName":"Tysoon Biryani","Spicy":2,"UnitPrice":"6.99","Qty":5,"DishTotal":"34.95"}',
} ]
I am trying to fetch few attributes from the above along with "Bags". But one important thing that i wanted to fetch is Url for the image of the dishes which is not specified in the "Bags" so i am parsing the "Bags" and running through loop to get the "DishId" which will be used to fetched the urls of image from another method with callback name getDishesByDishIds. The DishIds fetched are below:
[43]
[41, 42]
The method getDIshesByDishIds would fetch below results for above dish Ids when run through for loops:
[ TextRow {
DishId: 43,
DishImageUrl1:
'http://192.168.86.104:1111/images/dishImageUrl1_1602546024189.JPG'
} ]
[ TextRow {
DishId: 41,
DishImageUrl1:
'http://192.168.86.104:1111/images/dishImageUrl1_1602546024190.JPG'
},
TextRow {
DishId: 42,
DishImageUrl1:
'http://192.168.86.104:1111/images/dishImageUrl1_1602546024191.JPG'
} ]
The real issue i am facing is I am not getting the exact result as per shown below. The main problem i am facing is even though i am able to fetch the url for the dishes , i am not able to add the Urls to the final result as shown below:
{
"success": 1,
"bag": [
{
"DishOrderId": 163,
"BagId": "BPZDXT68148",
"DateCreated": "2021-05-27T03:55:05.000Z",
"Bags": [
{
"DishId": 43,
"DishName": "Kuchvi Biryani",
"Spicy": 2,
"UnitPrice": "6.99",
"Qty": 5,
"DishTotal": "34.95"
}
],
"Url": ['http://192.168.86.104:1111/images/dishImageUrl1_1602546024189.JPG']
},
{
"DishOrderId": 162,
"BagId": "BNJENZ08608",
"DateCreated": "2021-05-27T03:46:26.000Z",
"Bags": [
{
"DishId": 41,
"DishName": "Dum Biryani",
"Spicy": 2,
"UnitPrice": "6.99",
"Qty": 5,
"DishTotal": "34.95"
},
{
"DishId": 42,
"DishName": "Tysoon Biryani",
"Spicy": 2,
"UnitPrice": "6.99",
"Qty": 5,
"DishTotal": "34.95"
}
],
"Url": ['http://192.168.86.104:1111/images/dishImageUrl1_1602546024190.JPG',
'http://192.168.86.104:1111/images/dishImageUrl1_1602546024191.JPG']
}
]
}
The complete code is specified below:
myOrders: (req, res) => {
const userId = req.body.userId;
orderStatus = 2;
getAllOrdersByUserId(userId, orderStatus, (error, results) => {
if (error) {
console.log(error);
return res.status(500).json({
success: 0,
message: "Some other error",
error: error,
});
}
if (!results) {
return res.status(404).json({
success: 0,
message: "Record not found",
});
} else{
const myOrderArray = []; //this will be new array to store all details including dish Urls
console.log(results);
count = 0;
for (i = 0; i < results.length; i ) {
const myOrder = {}
myOrder.DishOrderId = results[i].DishOrderId;
myOrder.BagId = results[i].BagId;
myOrder.DateCreated = results[i].DateCreated;
myOrder.Bags = JSON.parse(results[i].Bags);
myOrderArray.push(myOrder);
OrderDishes = JSON.parse(results[i].Bags);
//for each one of dish in order dishes get the dish id
let dishId = []
DishUrls = [];
countz = 0;
for (j = 0; j < OrderDishes.length; j ) {
dishId.push(OrderDishes[j].DishId);
//fetch image url for the dish Id fetched
//DishUrls = [];
getDishesByDishIds(dishId, (error, getDishesByDishIdsResults) => {
if (error) {
console.log(error);
return res.status(500).json({
success: 0,
message: "Some other error",
error: error,
});
}
console.log(getDishesByDishIdsResults);
// DishUrls = [];
count2 = 0;
for (l = 0; l < getDishesByDishIdsResults.length; l ) {
count2 ;
if(getDishesByDishIdsResults[l].DishImageUrl1 == undefined){
if(count2 == getDishesByDishIdsResults.length){
//proceed with other steps
console.log(DishUrls);
}
}
else{
DishUrls.push(getDishesByDishIdsResults[l].DishImageUrl1);
}
}
});
countz ;
if(countz == OrderDishes.length){
//do next step
console.log(DishUrls);
myOrder.Url = DishUrls; //not working , coming incorrect
}
}
}
return res.json({
success: 1,
bag: myOrderArray,
});
}
});
},
};
Sorry for the long post, but I will really appreciate whoever wanted to help me because I am stuck here since few days.
CodePudding user response:
Disclaimer
Forgive me... I wrote this late night after an already LONG day at work...
I have no confidence in this code. It is untested, and is written very poorly. Probably won't work.
But...
I'm hopeful it gets you in the right direction at least.
Refactored Code
myOrders: (req, res) => {
const userId = req.body.userId;
let orderStatus = 2;
getAllOrdersByUserId(userId, orderStatus, (error, results) => {
if (error) {
console.log(error);
res.status(500).json({
success: 0,
message: "Some other error",
error: error,
});
return;
}
if (!results) {
res.status(404).json({
success: 0,
message: "Record not found",
});
return;
}
for (let i = 0; i < results.length; i ) {
(() => {
let currentOrder = results[i];
currentOrder.Bags = JSON.parse(currentOrder.Bags);
return new Promise((resolve, reject) => {
let dishIds = [];
for (let j = 0; j < currentOrder.Bags.length; j ) {
dishIds.push(currentOrder.Bags[j].DishId);
}
(() => {
return new Promise((innerResolve, innerReject) => {
getDishesByDishIds(dishIds, (error, getDishesByDishIdsResults) => {
let dishUrlResults = [];
if (error) {
innerReject("An error occurred during retrieval of the dish image urls");
return;
}
for (let l = 0; l < getDishesByDishIdsResults.length; l ) {
if (getDishesByDishIdsResults[l].DishImageUrl1 != undefined) {
dishUrlResults.push(getDishesByDishIdsResults[l].DishImageUrl1);
}
}
innerResolve(dishUrlResults);
});
});
})()
.then((urlResults) => {
currentOrder.Url = urlResults;
resolve();
})
.catch((innerPromiseError) => {
reject(innerPromiseError);
});
});
})()
.then(() => {
res.json({
success: 1,
bag: results,
});
})
.catch((promiseError) => {
//Could not complete the request
console.log(promiseError);
res.status(500).json({
success: 0,
message: "Some other error",
error: error,
});
});
}
});
}