0

Could someone explain how this is happening? An array from Express is being destroyed before it is returned. In the example below, I am successfully populating the resData.user.apps array and can see this via the server's console log. However, when the resData object is returned the array is empty:

// Build the response
var resData = {
    success: true,
    user: {
        email: newUserItem.email,
        apps: []
    }
};

// Add any default applications
Application.find({ isDefault: true, isDeleted: false }, function(err, defaultApps){
    if (err){
        console.log(err);
        return res.status(500).send({ message: 'Failure loading default applications.' });
    } else {
        if (defaultApps.length < 1){
            console.log('No default apps');
        } else {
            defaultApps.forEach(function(defaultApp){
                var app = {
                    name: defaultApp.formalName,
                    url: defaultApp.url,
                    def: true
                };

                console.log(app);
                resData.user.apps.push(app);

                console.log('Sanity: ' + JSON.stringify(resData));
            });
        }
    }
});

return res.send(resData);
Fred Lackey
  • 2,351
  • 21
  • 34
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Fraser Oct 12 '22 at 10:05

1 Answers1

-1

The problem here is that the find is async so you are writing back the response before the call has completed. Move return res.send(resData); into the find callback.

Application.find({ isDefault: true, isDeleted: false }, function(err, defaultApps){
    if (err){
        console.log(err);
        return res.status(500).send({ message: 'Failure loading default applications.' });
    } else {
        if (defaultApps.length < 1){
            console.log('No default apps');
        } else {
            defaultApps.forEach(function(defaultApp){
                var app = {
                    name: defaultApp.formalName,
                    url: defaultApp.url,
                    def: true
                };

                console.log(app);
                resData.user.apps.push(app);

                console.log('Sanity: ' + JSON.stringify(resData));

            });


        }
      res.send(resData);
    }
});
TGH
  • 38,769
  • 12
  • 102
  • 135