Answer the question
In order to leave comments, you need to log in
How to delay execution until condition is met?
The endpoint "/search" receives a variety of data from filters. I include the incoming data in the query object, the reserveNomersIds array is filled if the data arrived by date. How to delay the execution of Nomer.find(query) until reserveNomerIds is filled, that is, the if (req.body.from && req.body.to) condition is checked?
app.post('/api/search', function(req, res) {
var query = {}
var reserveNomersIds;
var filter = {}
//price
if (req.body.min && req.body.max) {
query.cost_per_night = {$gte: req.body.min, $lte: req.body.max}
//по возрастанию
filter.cost_per_night = 1
}
//dates
if (req.body.from && req.body.to) {
Reservation.distinct("nomer", {from: {$lt: new Date(req.body.to)}, to: {$gt: new Date(req.body.from)} }
).then((data, err) => {
reserveNomersIds = data;
})
}
if (req.body.guests > 1) {
query.occupancy = {$gte: req.body.guests}
}
if (req.body.search) {
query.city = { $regex: req.body.search.toLowerCase() }
}
Nomer
.find({ _id: { $nin: reserveNomersIds}, query})
.sort(filter)
.then(function (err, result) {
if(err){
res.send(err);
} else {
res.json(result);
}
})
})
Answer the question
In order to leave comments, you need to log in
Is it not possible in modern Javascript?
app.post('/api/search', async function(req, res) {
var query = {}
var reserveNomersIds;
var filter = {}
//price
if (req.body.min && req.body.max) {
query.cost_per_night = {$gte: req.body.min, $lte: req.body.max}
//по возрастанию
filter.cost_per_night = 1
}
//dates
if (req.body.from && req.body.to) {
reserveNomersIds = await Reservation.distinct("nomer", {
from: {
$lt: new Date(req.body.to)},
to: {$gt: new Date(req.body.from)
}
});
}
if (req.body.guests > 1) {
query.occupancy = {$gte: req.body.guests}
}
if (req.body.search) {
query.city = { $regex: req.body.search.toLowerCase() }
}
try {
var result = await Nomer
.find({ _id: { $nin: reserveNomersIds}, query})
.sort(filter);
res.json(result);
} catch (e) {
res.send(e);
}
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question