Reputation: 655
so im currently testing my query where specific data will be fetched if it matches the required parameters.
router.get('/getNewWatch/:sdate/:shft/:type', function(req, res){
reqDate = req.params.sdate;
reqShift = req.params.shft;
reqType = req.params.type;
var watcher = database.ref('watch');
watcher.once('value', function(snapshot){
var promises = [];
snapshot.forEach(function(childSnapshot){
promises.push(new Promise((resolve, reject) =>{
resolve({
childKey: childSnapshot.key,
childData: childSnapshot.val()
});
}));
});
Promise.all(promises).then(function(snapshot){
var dataSet = [];
snapshot.forEach(function(result){
if(result.childData.availability != 'undefined'){
if(result.childData.availability[reqDate]){
res.send('yes we have');
}else{
res.send('no we dont');
}
}else{
res.send('no available watchers');
}
});
res.json(dataSet);
})
});
});
1st is im trying to filter if child available exist on my data. then next is to filter if date matched the requiredDate. my data looks like this
watch
| --- 12i3g1uy2g412u
| ----available
| -----2018-02-01
|----isGood: "true"
|----shft: "Night"
| --- jh2g53hjg535hg
| --- 7i8hi79u89hui5
| ----available
| -----218-02-02
|----isGood:"false"
|----shft:"Day"
the response is good i got the correct response based on condition but my problem is when it returns the reponse it also return this error on my console.. UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property '2018-02-07' of undefined
Upvotes: 0
Views: 1542
Reputation: 10111
Try this
router.get('/getNewWatch/:sdate/:shft/:type', function (req, res) {
reqDate = req.params.sdate;
reqShift = req.params.shft;
reqType = req.params.type;
var watcher = database.ref('watch');
watcher.once('value', function (snapshot) {
var promises = [];
snapshot.forEach(function (childSnapshot) {
promises.push(new Promise((resolve, reject) => {
resolve({
childKey: childSnapshot.key,
childData: childSnapshot.val()
});
}));
});
Promise.all(promises).then(function (snapshot) {
var dataSet = {};
snapshot.forEach(function (result, index) {
if (result.childData.availability) {
if (result.childData.availability[reqDate]) {
dataSet['childData-' + index] = 'yes we have'; // instead of 'childData-'+index you can give user friendly key.
} else {
dataSet['childData-' + index] = 'no we dont';
}
} else {
dataSet['childData-' + index] = 'no available watchers';
}
});
res.json(dataSet);
})
});
});
Output will be something like:
{
"childData-1": "yes we have",
"childData-2": "no we dont",
"childData-3": "no available watchers",
}
Upvotes: 1