我试图将我的头放在节点JS及其异步操作的思想上。我正在使用节点JS和Express设置Web服务器,其中该服务器获取两对x,y
坐标并发送查询结果作为响应。
我有三个职能。 firstFunction
将x,y
坐标拆分为单个float值。 secondFunction
根据坐标从我的数据库中选择最近的Node。 (此函数应调用两次,因为我要传递两对x,y
坐标。最后,thirdFunction
使用secondFunction
的输出值来计算某些内容。
function firstFunction(start, end) {
start = start.split(",")
end = end.split(",")
lng1 = parseFloat(start[0])
lat1 = parseFloat(start[1])
lng2 = parseFloat(end[0])
lat2 = parseFloat(end[1])
return { x1: lng1, y1: lat1, x2: lng2, y2: lat2};
}
//returns an integer value
function secondFunction(x, y) {
var qstr = 'select * from _a_getnearestnode(' + x + ',' + y + ')'
client.query(qstr, function(err, result){
if (err) {
throw err
} else {
return result
}
});
}
function thirdFunction(nodeFrom, nodeTo) {
var qstr = 'select ROW_NUMBER() OVER () AS gid, st_union(the_geom) as the_geom, sum(cost_s) as cost_s, sum(length_m) as length_m FROM _a_route_speed(' +
nodeFrom + ',' + nodeTo + ')'
client.query(qstr, function(err, result) {
if (err) {
throw err
} else {
return result
}
});
}
exports.mainFunction = function (req, res, next) {
start = req.body.from
end = req.body.to
//take result of firstfunction and put result as parameter into second function
//call second function twice as first function outputs two pairs of x,y coordinates
//call third function and put result of secondfunction into thirdfunction
//send result of thirdfunction to client
}
问题1:如何为这三个功能建立承诺链?
问题2:我必须调用第二个函数两次才能传递四个坐标