简体   繁体   中英

Getting JSON from a Function in javascript

So this will be a lot of code, but what matter is on line 22-25, and line 87-91. The rest of the code works. I have a nested function and want to return the JSON string. Using console.log I can tell it is running properly but will not return the JSON string. Look for the part that says //---------this part-------. There are two parts that I am asking about.

exports.post = function(request, response) {

    var mssql = request.service.mssql;       
    //var data = '{"userID":"ryan3030@vt.edu1"}';
    var inputJSON = request.body.JSONtext;
    var json = JSON.parse(inputJSON);
    var userID = json.userID;

    mssql.query("EXEC getMeetingInfo ?", [userID],  
    {
        success: function(results3) {    
            var meetingsToday = results3.length;

            var meetingID = results3[0].meetingID;
            var meetingName = results3[0].meetingName;
            var meetingDescription = results3[0].meetingDescription;
            var meetingLength = results3[0].meetingLength;
            var meetingNotes = results3[0].meetingNotes;
            var hostUserID = results3[0].hostUserID;

//--------------------------------------THIS PART------------------------------        
      var JSONfinal = allInfoFunction(mssql, meetingID, userID, meetingName, meetingDescription, meetingLength, meetingNotes, hostUserID, meetingsToday);                     
      console.log(JSONfinal);//DOES NOT WORk
      response.send(statusCodes.OK, JSONfinal);//DOES NOT WORK
//---------------------------------BETWEEN THESE----------------------------------                
      },
      error: function(err) {
            console.log("error is: " + err);
            response.send(statusCodes.OK, { message : err });
      }
    });

};

function allInfoFunction(mssql, meetingID, userID, meetingName, meetingDescription, meetingLength, meetingNotes, hostUserID, meetingsToday){
    mssql.query("EXEC getLocation ?", [meetingID],  
                { success: function(results2) {
                            var meetingLocation = results2[0].meetingLocation;
                            var JSONlocation = {"meetingLocation": meetingLocation};

                                mssql.query("EXEC getDateTime ?", [meetingID],  
                                { success: function(results1) {
                                            var length = results1.length;
                                            var dateTime = [];
                                            dateTime[0] = results1[0].meetingDateTime;
                                            for (var x= 1; x < length; x++) {
                                                dateTime[x] =  results1[x].meetingDateTime;
                                            }
                                            //console.log(dateTime);

                                                mssql.query("EXEC getDateTimeVote",  
                                                { success: function(results) {
                                                        //console.log(results);
                                                        var JSONoutput2 = {};
                                                        var JSONtemp = [];
                                                        var length2 = results.length; 
                                                        for(var j = 0; j < length; j++){
                                                            var vote = false;
                                                            var counter = 0;
                                                            for(var z = 0; z < length2; z++){
                                                                var a = new Date(results[z].meetingDateTime);
                                                                var b = new Date(results1[j].meetingDateTime);
                                                                if(a.getTime() === b.getTime()){
                                                                    counter = counter + 1;
                                                                }
                                                                if((a.getTime() === b.getTime()) && (results[z].userID == userID)){
                                                                    vote = true;
                                                                }
                                                            }
                                                            var meetingTimeInput = {"time": b, "numVotes": counter, "vote": vote}
                                                            JSONtemp.push(meetingTimeInput);
                                                            JSONoutput2.meetingTime = JSONtemp;

                                                        }

                                                        var JSONfinal = {};
                                                        var mainInfoArray = [];

                                                        var JSONmainInfo = {meetingID: meetingID, meetingName: meetingName, meetingDescription: meetingDescription, meetingLength: meetingLength, meetingNotes: meetingNotes, hostUserID: hostUserID, meetingLocation: meetingLocation };
                                                        JSONmainInfo.meetingTime = JSONtemp;

                                                        JSONfinal.numMeetingsToday = meetingsToday;
                                                        mainInfoArray.push(JSONmainInfo);
                                                        JSONfinal.meetingList = mainInfoArray;
                                                        //response.send(statusCodes.OK, JSONfinal);

//---------------------------------------AND THIS PART-------------------------------                                                        
                                                        console.log(JSON.stringify(JSONfinal));//This outputs the correct thing
                                                        var lastOne = JSON.stringify(JSONfinal);
                                                        return lastOne; //ths dosent work 
//-------------------------------------BETWEEN THESE-----------------------------------

                                                },
                                                  error: function(err) {
                                                        console.log("error is: " + err);
                                                        //response.send(statusCodes.OK, { message : err });
                                                  }
                                                });       
                                },
                                  error: function(err) {
                                        console.log("error is: " + err);
                                        //response.send(statusCodes.OK, { message : err });
                                  }
                                });          
                },
                  error: function(err) {
                        console.log("error is: " + err);
                        //response.send(statusCodes.OK, { message : err });
                  }
                });
}

I've done a little refactoring to your code to take a more modular approach. It becomes quite tricky to debug something like what you have above. Here it is:

exports.post = function(request, response) {
    var mssql = request.service.mssql;       
    var inputJSON = request.body.JSONtext;
    var json = JSON.parse(inputJSON);
    var userID = json.userID;

    var JSONFinal = {};

    getMeetingInfo(userID);

    function getMeetingInfo(userID){    
        mssql.query("EXEC getMeetingInfo ?", [userID], {
            success: function(results){
                JSONFinal.meetingsToday = results.length;
                JSONFinal.meetingID = results[0].meetingID;
                JSONFinal.meetingName = results[0].meetingName;
                JSONFinal.meetingDescription = results[0].meetingDescription;
                JSONFinal.meetingLength = results[0].meetingLength;
                JSONFinal.meetingNotes = results[0].meetingNotes;
                JSONFinal.hostUserID = results[0].hostUserID;

                // Call next function
                getLocation(JSONFinal);
            },
            error: function(err) {
                console.log("error is: " + err);
                response.send(statusCodes.OK, { message : err });
            }
        });
    }

    function getLocation(){
        mssql.query("EXEC getLocation ?", [JSONFinal.meetingID], { 
            success: function(results) {
                JSONFinal.meetingLocation = results[0].meetingLocation;

                // Call next function
                getDateTime(JSONFinal);
            },
            error: function(err) {
                console.log("error is: " + err);
            }
        });     
    }

    function getDateTime(){
        mssql.query("EXEC getDateTime ?", [JSONFinal.meetingID], { 
            success: function(results) {
                var length = results.length;
                var dateTime = [];
                for (var x= 0; x < length; x++) {
                    dateTime[x] =  results[x].meetingDateTime;
                }

                // Call next function
                getDateTimeVote(dateTime);
            },
            error: function(err){
                console.log("error is: " + err);    
            }
        });                                  
    }

    function getDateTimeVote(dateTime){
        mssql.query("EXEC getDateTimeVote", { 
            success: function(results) {
                var JSONtemp = [];
                var length2 = results.length; 

                for(var j = 0; j < dateTime.length; j++){
                    var vote = false;
                    var counter = 0;
                    for(var z = 0; z < length2; z++){
                        var a = new Date(results[z].meetingDateTime);
                        var b = new Date(results1[j].meetingDateTime);
                        if(a.getTime() === b.getTime()){
                            counter = counter + 1;
                        }
                        if((a.getTime() === b.getTime()) && (results[z].userID == userID)){
                            vote = true;
                        }
                    }
                    var meetingTimeInput = {"time": b, "numVotes": counter, "vote": vote}
                    JSONtemp.push(meetingTimeInput);
                }

                var JSONmainInfo = {
                    meetingID: JSONFinal.meetingID, 
                    meetingName: JSONFinal.meetingName, 
                    meetingDescription: JSONFinal.meetingDescription, 
                    meetingLength: JSONFinal.meetingLength, 
                    meetingNotes: JSONFinal.meetingNotes, 
                    hostUserID: JSONFinal.hostUserID, 
                    meetingLocation: JSONFinal.meetingLocation 
                    meetingTime: JSONtemp
                };

                var JSONfinal = {
                    numMeetingsToday: JSONFinal.meetingsToday,
                    meetingsList: [JSONmainInfo]
                };

                // Call next function
                sendResponse(JSON.stringify(JSONfinal));
            },
            error: function(err) {
                console.log("error is: " + err);
            }
        });   
    }

    function sendResponse(data){
        response.send(statusCodes.OK, data);
    }
};

It looks a lot different but the functionality is pretty much the same. The key point if you look at the code is that each subsequent function is executed only after the success of the previous function. This effectively chains the methods together so that they are always executed in order and is the key point of difference.

One thing to note here is the similarity between your

allInfoFunction(...

and my

getMeetingInfo(userID)

Both of these will return undefined more or less immediately, after the MSSQL query is sent to the server. This is because the request is fired asynchronously, and the javascript continues to run through the code. After it's fired of the asynchronous request, it has nothing left to do in that function, so it returns. There is no return value specified so it returns nothing (or undefined if you will).

So all in all, the code in the question code will return undefined and then attempt to send a response before anything has actually happened. This code fixes that problem by firing the sendResponse after all the queries have been executed.

I refactored this code in a text editor and haven't run it, or checked it for errors, so follow the basic outline all you like but it may not be a good idea to copy and paste it without checking it's not broken

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM