0

I am trying to search available objects of a MongoDB collection(e.g. ParkingSpot) using specific business logic, the problem is that inside this function which is an async/await func I am looking inside another collection with .find() which I use as an async/await as well. The second function doesn't execute and gets back as an promise " Promise { } " and therefore the business logic is not applied. Can you help me please? Here is 1st function:

exports.get_parkingSpots_avail_for_parking = async (req, res, next) => {
    try {
        const radius = req.body.radius;
        const userLatitude = req.body.userLatitude;
        const userLongitude = req.body.userLongitude;
        const reqStartDate = new Date(req.body.reqStartDate);
        const reqEndDate = new Date(req.body.reqEndDate);



        const parkingSpots = await ParkingSpot.find({
            isAvailable: true
        }, (err, parkingSpots) => {
            if (err) {
                return res.status(500).json({
                    error: err
                });
            }
            const freeParkingSpots = parkingSpots.filter(parkingSpot => {
                return distanceCalculator(parkingSpot.latitude, parkingSpot.longitude, userLatitude, userLongitude) < radius
            })
            const availParkingSpots = freeParkingSpots.filter( freeParkingSpot => {
               // console.log(freeParkingSpot._id);
                console.log(isParkingAvailable(reqStartDate, reqEndDate, freeParkingSpot._id));
                return isParkingAvailable(reqStartDate, reqEndDate, freeParkingSpot._id);
            })            
        }).select('_id userId number address latitude longitude notes isAvailable startOfAvailability endOfAvailability');

        console.log(parkingSpots);
        if (parkingSpots.length > 0) {
            return res.status(200).json({
                parkingSpots: parkingSpots
            });
        }
        return res.status(404).json({
            message: "No available parking spots for requeste period"
        });

    } catch (err) {
        res.status(500).json({ 
            error: err
        })
    }
};

Second function which is being called :
module.exports = async function isParkingAvailable(reqStartDate, reqEndDate, parkingSpotId) {
    const parkingSpotBookings =  await Booking.find({ parkingSpotId: parkingSpotId})
        .select('_id parkingSpotId sharerUserId renterUserId startDate endDate');
    if (parkingSpotBookings.length == 0) {
        return true;
    }
    parkingSpotBookings.filter(booking => {
        //console.log(parkingSpotId);
        //console.log("Is overlapping" +!isOverlapping(reqStartDate, reqEndDate, booking.startDate, booking.endDate));
        return !isOverlapping(reqStartDate, reqEndDate, booking.startDate, booking.endDate)
    })
}

So the problem is that calling second function appears as that in console.log :Promise { }

1 Answer 1

2

Await will Return the result to your parkingSpot variable. For the second function: You have defined this function as an async, that means it is holding asynchronous process, and in Node JS es6 async process is processed as a promise, so if you won't call it with await it will return a promise only

exports.get_parkingSpots_avail_for_parking = async (req, res, next) => {
    try {
        const radius = req.body.radius;
        const userLatitude = req.body.userLatitude;
        const userLongitude = req.body.userLongitude;
        const reqStartDate = new Date(req.body.reqStartDate);
        const reqEndDate = new Date(req.body.reqEndDate);

        const parkingSpots = await ParkingSpot.find({isAvailable: true}).select('_id userId number address latitude longitude notes isAvailable startOfAvailability endOfAvailability');
        const freeParkingSpots = parkingSpots.filter(parkingSpot => {
            return distanceCalculator(parkingSpot.latitude, parkingSpot.longitude, userLatitude, userLongitude) < radius
        });
        const availParkingSpots = freeParkingSpots.filter( async freeParkingSpot => {
            /* You have defined this function as an async, that means it is holding asynchronous process, and in 
Node JS es6 async process is processed as a promise, so if you won't call it with await it will return a promise only */
            return await isParkingAvailable(reqStartDate, reqEndDate, freeParkingSpot._id);
        });

        if (parkingSpots.length > 0) {
            return res.status(200).json({
                parkingSpots: parkingSpots
            });
        }
        return res.status(404).json({
            message: "No available parking spots for requeste period"
        });

    } catch (err) {
        res.status(500).json({
            error: err
        })
    }
};

I hope it will help you.

Thank you

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I got it now, I knew it second isParkingAvailable(...) function returns a promise but I thought once I declare it with async() { await...} I don't have to wrap it inside an async/await function... but now I realise I used async/await at declaring for Booking.find() not for itself. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.