Azure移动服务 - 从两个表读取并返回自定义响应对象

时间:2015-06-22 22:32:55

标签: javascript azure azure-mobile-services

我正在使用名为customertickets的JavaScript后端编写Azure移动服务(AMS)API,并且在.get函数中我试图从我的AMS中的两个表中读取值。

这两个表格是' User'和' Ticket'我试图根据传递的参数(phonenumber)检索所有票据并返回一些统计数据。此外,如果票证满足特定条件(item.parsedjsondata.SPId不为null或为空),则在循环遍历票证时会注入自定义返回值item.spname

这是完整的代码(ctrl + F'这不工作!'):

//Get ticket info by customer phonenumber
exports.get = function(request, response) {
    var phonenumber = request.query.phonenumber;
    var activeTicketsCounter = 0;
    var completedTicketsCounter = 0;
    var canceledTicketCounter = 0;
    var needCustomerRatingTicketCounter = 0;
    var includeCounterData = request.query.includeCounterData;


    console.log("customertickets/get phonenumber: " + phonenumber);

    request.service.tables.getTable('Ticket').read({
        //SEE: http://stackoverflow.com/questions/24406110/how-to-get-system-properties-createdat-version-in-javascript-backend-of-azu
        systemProperties: ['__createdAt', '__updatedAt'],
        success: function(result) {

            //No ticket is found
            if (result.length === 0) {
                console.log("customertickets/get: no ticket found");
                response.send(statusCodes.NOT_FOUND, { message: "customertickets/get: no ticket is found" });

            }
            //return tickets after filtration based on the customer phonenumber
            else {
                console.log("customertickets/get: ticket found");
                var filteredResults = [];
                result.forEach(function(item) {
                    //only tickets with matched phonen number
                    if (JSON.parse(item.jsondata).customerPhonenumber == phonenumber) {
                        console.log(item);

                        //Adding parsed jsondata to item
                        item.parsedjsondata = JSON.parse(item.jsondata);

                        //Adding the name of the assigned spid; only if spid is not null ie. ticket is already assinged
                        if (item.parsedjsondata.SPId) {

                            console.log("SPID", item.parsedjsondata.SPId);
                            console.log("customerId", item.parsedjsondata.customerId);

                            //This works as expected
                            item.spid = item.parsedjsondata.SPId;

                            request.service.tables.getTable('User').where({ id: item.parsedjsondata.SPId.toString(), usertype: "200" }).read({

                                success: function(userResults) {
                                    console.log('result', userResults[0]);
                                    //Does not exist; return NOT FOUND as sp name!
                                    if (userResults.length === 0) {
                                        //This wroks fine and logs the expected result
                                        console.log("customertickets/get: not SPname found", item.parsedjsondata.SPId);
                                        //THIS DOES NOT WORK!
                                        item.spname = "Service Provider Name Not Found";
                                    }
                                    //Record exists; return it
                                    else {
                                        //This wroks fine and logs the expected result
                                        console.log("retrieved spname", JSON.parse(userResults[0].userjsondata).businessData.businessname.ar);
                                        //THIS DOES NOT WORK!
                                        item.spname = JSON.parse(userResults[0].userjsondata).businessData.businessname.ar;
                                    }

                                }
                            });


                        }


                        //ActiveTicketsCounter
                        if (item.parsedjsondata.ticketStatus == "TicketStatus_ToBeAssigned"
                            || item.parsedjsondata.ticketStatus == "TicketStatus_IsAssigned"
                            || item.parsedjsondata.ticketStatus == "TicketStatus_InProgress"
                            || item.parsedjsondata.ticketStatus == "TicketStatus_SPDisputed_CustomerNotReachable"
                            || item.parsedjsondata.ticketStatus == "TicketStatus_SPDisputed_OutOfScope"
                            || item.parsedjsondata.ticketStatus == "TicketStatus_SPDisputed_CustomerCanceled"
                            || item.parsedjsondata.ticketStatus == "TicketStatus_SPDisputed_PriceDisagreement") {
                            activeTicketsCounter++;
                        }

                        //needCustomerRatingTicketCounter
                        if (item.parsedjsondata.ticketStatus == "TicketStatus_Completed_No_Customer_Rating") {
                            needCustomerRatingTicketCounter++;
                        }

                        //CompletedTicketsCounter
                        if (item.parsedjsondata.ticketStatus == "TicketStatus_Completed_And_Customer_Rated") {
                            completedTicketsCounter++;
                        }

                        //canceledTicketCounter
                        if (item.parsedjsondata.ticketStatus == "TicketStatus_CanceledByB8akAgent") {
                            canceledTicketCounter++;
                        }

                        //Testing: it works!
                        item.testing = "Testing Something!";

                        console.log("item.spname before push:", item.spname);
                        //pushing the found item to the list of results
                        filteredResults.push(item);
                    }
                });

                console.log("includeCounterData: " + includeCounterData);

                if (includeCounterData == true) {
                    //After the loop, add the counters to the filteredresults to be returned
                    filteredResults.push({
                        activeTickets: activeTicketsCounter,
                        pendingCustomerRatingTickets: needCustomerRatingTicketCounter,
                        completedTickets: completedTicketsCounter,
                        canceledTickets: canceledTicketCounter
                    });
                }



                response.send(statusCodes.OK, filteredResults);
            }

        }
    });
};

我的主要问题是item.spname永远不会分配值,也不会在响应中返回。我可以看到item.spname的指定值JSON.parse(userResults[0].userjsondata).businessData.businessname.ar在AMS日志中成功记录,但在响应中没有返回。

1 个答案:

答案 0 :(得分:1)

您遇到的问题是您没有等待多次调用

的结果
request.service.tables.getTable('User').where(...).read(...

在将响应发送回客户端之前到达。请记住,node.js / JavaScript后端中的几乎所有内容都是异步的。当你在User表上调用read时,它不会在执行下一个语句之前等待结果到达 - 相反,它会对操作进行排队,这样当响应可用时,它将被执行

要解决此问题,您需要对用户表进行所有read次调用,并且只有在您获得所有回调后,才能调用response.send。< / p>