如何在自定义 API 中使用 JavaScript 遍历 Azure 移动服务 Table

How to loop through Azure Mobile Service Table using JavaScript in a Custom API

我想访问 Azure 移动服务自定义 API 中 table 中的所有行,提取特定列的值并对它们执行一些操作。在 JavaScript?

中如何在句法上做到这一点

到目前为止我所做的是:

exports.post = function(request, response) {    
var tables = request.service.tables;

var eventIdString=request.body.EventId;
var LongClientString = request.body.Longitude;
var LatClientString = request.body.Latitude;
var eventId = parseFloat(eventIdString);
var longClient = parseFloat(LongClientString);
var latClient = parseFloat(LatClientString);

var mssql = request.service.mssql;
var sql = "SELECT * FROM User";

var str="";

mssql.query(sql, {
    success: function(results) {
        for(var i=0; i<results.length; i++)
        {
            var longServerString = results[i].longitude;
            var latServerString = results[i].latitude;
            var longServer = parseFloat(longServerString);
            var latServer = parseFloat(latServerString);

            var distance = getDistanceInKm(latClient, longClient, latServer, longServer);

            if(distance<20)
            {
                str=str+results[i].name+",";
            } 
        }
    }});    

response.send(statusCodes.OK, { message : str }); 

//calculating distace
function getDistanceInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1);  // deg2rad below
var dLon = deg2rad(lon2-lon1); 
var a = 
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
Math.sin(dLon/2) * Math.sin(dLon/2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c; // Distance in km
return d;
}

function deg2rad(deg) {
return deg * (Math.PI/180)
} };

但我在 'str' 中一无所获。我做错了什么??

您的代码中的问题是您在使用 str 变量之前没有等待 mssql.query 调用的结果。就像 node.js-land 中的几乎所有东西一样,query 是一个异步操作,所以当它 returns 时,成功回调还没有被调用。

尝试将 response.send 调用移动到回调内部,您应该会开始看到一些结果。

mssql.query(sql, {
    success: function (results) {
        for(var i = 0; i < results.length; i++)
        {
            var longServerString = results[i].longitude;
            var latServerString = results[i].latitude;
            var longServer = parseFloat(longServerString);
            var latServer = parseFloat(latServerString);

            var distance = getDistanceInKm(latClient, longClient, latServer, longServer);

            if(distance < 20)
            {
                str = str + results[i].name + ",";
            }
        }
        response.send(statusCodes.OK, { message : str });
    }
});