gpt4 book ai didi

node.js - 以同步方式执行异步进程 | Node.js |谷歌地图

转载 作者:太空宇宙 更新时间:2023-11-03 23:30:38 25 4
gpt4 key购买 nike

这个问题与之前发布的关于异步进程的问题不同。我正在开发一个类似 uber 的应用程序,并且使用 firebase 作为后端。我制作了一个服务器来处理一些任务,例如向司机分配订单。当订单出现时,我需要使用谷歌地图 API 找到所有司机和客户之间的距离。下面是我用来计算司机和顾客之间距离的函数。

    function calculatingDistance(fromLat,fromLong,toLat,toLong){
var distanceDurationObject={};
var options = {
host: 'maps.googleapis.com',
path: '/maps/api/directions/json?origin='+fromLat+','+fromLong+'&destination='+toLat+','+toLong+'&key=AIzaSyBsoc1PZOItqHNYc5z2hW_ejPFi2piRR8Y',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};

var req = https.get(options, function(res) {
//buffering alll data
var bodyChunks = [];
res.on('data', function(chunk) {
// You can process streamed parts here...
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
json = JSON.parse(body);
//parsing json returned
var routes =json["routes"];
var legsObject=routes[0].legs;
var legsFirstArray=legsObject[0];
//Our Required Distance between two points
var distanceValue=legsFirstArray.distance.value;
var durationValue=legsFirstArray.duration.value;
console.log(distanceValue+" "+durationValue);
distanceDurationObject.distance=distanceValue;
distanceDurationObject.duration=durationValue;

});
});

req.on('error', function(e) {
console.log('ERROR: ' + e.message);
//try to add this error to a file
});
}

下面给出了查找顾客和出租车司机之间距离的流程。

1) 一旦订单出现在数据库中,它就会被提取到服务器中并保存在一个 map 中,该 map 包含作为客户 ID 的键和作为提供客户纬度和经度的对象的值。

2)还有一个 map ,其中包含作为驾驶员 ID 的键和作为包含驾驶员纬度和经度的对象的值。

3)使用上面给出的函数计算客户与所有司机的距离,距离最短的一位司机会收到通知。

问题:

我想要的是,一旦订单出现,在 for 循环中,我在队列中添加“calculateDistance(fromLat,fromLong,toLat,toLong)”函数,其中 toLat 和 toLong 具有驾驶员的纬度和经度,而 fromLat 和 fromLong 具有客户的纬度和经度。在 for 循环之后,我执行所有回调,一旦所有这些回调完成,就会调用函数 x(),并将所有这些回调的持续时间对象返回到函数 x();

TL;DR 基本上我只想在完成执行后将所有异步函数中的数据放入一个函数中。

最佳答案

您正在寻找Promise.all .

关于node.js - 以同步方式执行异步进程 | Node.js |谷歌地图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38582057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com