0

The following code is returning undefined when I attempt to execute the error, callback capability. I don't understand why the json isn't returning as the console log outputs the complete query.

Here is the invoked function that is producing the json into the log.


exports.getThem = (req) => {
    var addy = req.body.email;

    Picks.findOne({ 'email' :  addy }, (err, theResults) => {
        if (err) {
            return ({ 'msg': err });
        } 


        console.log("made the query " + JSON.stringify(theResults)); 
        return theResults;
    });
}; 

Above, theResults print "made the query " and a complete JSON string.

The invoking code will execute and return to Postman the following JSON without the theResults JSON.

The console.log "log this" never executes and the 2nd log prints "after the log" undefined.


{
  "token" : someCrazyLookingToken 
}

exports.loginUser = (req, res) => {

         var theResults;

          theResults = Picks.getPicks( req ,  ( err , thePicks)  => {
                    console.log("log this" + JSON.stringify(thePicks));                    
                    if (!err){
                        console.log ("what happened" + err)
                    }
         });
         console.log("after the call " + JSON.stringify(theResults));                    
         return res.status(200).json({  picks: thePicks, token: createToken(user) });
}

Why? Is there a timing issue I'm not waiting for in the callback?

Reacting
  • 27
  • 1
  • 8
  • 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) – Marcos Casagrande Dec 11 '19 at 19:49

1 Answers1

0

It's not necessarily a timing issue, but perhaps a misunderstanding on your part in how callbacks work, particularly in their scope. In your code, theResults is never going to have a value.

Try setting it up like this, and read up on promises and callbacks to get a better understanding on both.

exports.loginUser = async (req, res) => {
    try {
        const theResults = await new Promise((resolve, reject) => {
            Picks.getPicks(req, (err, thePicks) => {
                if (err) {
                    return reject(err);
                }
                return resolve(thePicks);
            })
        });

        return res.status(200).json({picks: theResults, token: createToken(user)});
    } catch (err) {
        //handle err
    }
}
Michael Rodriguez
  • 2,142
  • 1
  • 9
  • 15