Skip to content
Advertisement

Async and promise function do not display anything in my res.json call

I have a controller in javascript which should get a given user, and then the pets that are associated with the user. The related pets are stored in an array of object refs within the user schema. At the minute, when I try to res.json the resulting array containing the related pets, it outputs as an empty array ‘[]’. Following the Mozilla docs and tutorials I have tried to implement a promise on this function to combat my previous issue of the res.json outputting an empty array. I’m not sure where I am going wrong as I am a newbie to JS/express/node/mongo

Problem code:

     export const getPetsForAUser = (req, res)=>
    {
        function getter(){
            return new Promise(resolve =>{
           User.findOne({_id: req.params._id}, (err, users) =>{
               
                let petlist = users.pets;
                for(var i = 0; i < petlist.length; i++){
            Pet.findOne({_id:petlist[i]}, (err, pet) =>{
                var t = pet
                   
                    return Promise.resolve(t)
                    
            });
        }
    })
       
                
                
        });
    
    
    }
    async function asyncCall(){
        const result = await getter();
        res.json(result);
    }
    
    asyncCall();
    
    };


Advertisement

Answer

Using Aync/Await and Promise all

export default async (req, res) => {
const promises = [];
let result = null;

const petlist = await new Promise((resolve, reject) => {
    User.findOne({ _id: req.params._id }, (err, users) => {
        if (err) {
            reject(err);
        } else {
            resolve(users.pets);
        }
    });
});

if (petlist && petlist.length) {
    for (let i = 0; i < petlist.length; i++) {
        // eslint-disable-next-line no-loop-func
        const promise = new Promise((resolve, reject) => {
            Pet.findOne({ _id: petlist[i] }, (err, pet) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(pet);
                }
            });
        });
        promises.push(promise);
    }

    result = await Promise.all(promises).then((data) => {
        console.log('all promises resolved!');
        console.log(data);
        return data;
    });
}

console.log(result);

};
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement