简体   繁体   English

从JavaScript中的函数获取JSON

[英]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. 因此,这将是很多代码,但是重要的是第22-25行和第87-91行。 The rest of the code works. 其余代码工作正常。 I have a nested function and want to return the JSON string. 我有一个嵌套函数,想返回JSON字符串。 Using console.log I can tell it is running properly but will not return the JSON string. 使用console.log可以告诉它运行正常,但是不会返回JSON字符串。 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. 在将MSSQL查询发送到服务器后,这两个函数都会立即或多或少返回undefined This is because the request is fired asynchronously, and the javascript continues to run through the code. 这是因为请求是异步触发的,而javascript会继续在代码中运行。 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). 没有指定return值,因此它不返回任何值(如果愿意,则undefined )。

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. 此代码通过在执行所有查询后触发sendResponse解决此问题。

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 我在文本编辑器中重构了此代码,但没有运行它,也没有检查它是否有错误,因此请按照自己喜欢的基本大纲进行操作,但复制并粘贴它而不检查其是否损坏可能不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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