以同步方式执行asynchronous进程| Node.js | Google地图

这个问题不同于以前发布在asynchronous进程上的问题。 我正在开发一个类似于应用程序的超级应用程序,而且我正在使用Firebase作为后端。 我做了一个服务器来处理一些任务,比如给司机下达命令。 当一个订单出现,我需要find所有的司机和客户之间使用谷歌地图API的距离。 下面是我用来计算驾驶员和客户之间距离的function。

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 }); } 

发现客户和出租车司机之间的距离的stream量给出了波纹pipe。

1)一旦订单出现在数据库中,它将被提取到服务器中,并保存在一个包含客户和客户的纬度和经度对象的key中,

2)还有一个地图,其中包含作为驱动程序的id和作为包含驱动程序的纬度和经度的对象的值。

3)使用上面给出的函数计算所有驾驶员的顾客距离,并且距离最近的一个驾驶员接收到通知。

问题:

我想要的是,一旦顺序出现,在一个for循环中,我添加了“计算距离(fromLat,fromLong,toLat,toLong)”函数与toLat和toLong具有纬度和经度的驱动程序,fromLat和fromLong有经度和纬度的客户。 在for循环之后,我执行所有的callback函数,一旦所有的callback函数都完成了,函数x()被调用,所有callback函数的距离durationObject被返回给函数x()。

TL; DR基本上我只是想在所有的asynchronous函数完成执行后把数据放到一个函数中。

你正在寻找Promise.all 。

你可以使用asynchronous库来实现你所需要的。 这个库有广泛的同步任务function。 例如async.waterfallasync.series可以在这里完成这项工作。 您可以在您的callback函数中使用它们以实现同步行为。