循环javascript nodejs中的asynchronous函数

我需要扫描行程数组并计算当前行程与数组中每次行程之间的行程时间,并select最短行程时间。 为了计算,我需要发送谷歌地图API调用。

我非常困惑asynchronouscallback函数。 任何人都可以帮助我如何发送循环内的API调用,并检查结果,并继续?

谢谢。

旅行是在我的数组列表中;

arrays:

array=[trip1,trip2, trip3,....]; 

JS:

 function assigntrips(array){ var triplist = []; for(var i=0; i< array.length; i++){ var fstnode = array[i]; for(var j=i+1; j<array.length; j++){ //here i want to get the response from google api and decide if i want to choose the trip. if not the for loop continues and send another api call. } } } function apicall(inputi, cb){ var destination_lat = 40.689648; var destination_long = -73.981440; var origin_lat = array[inputi].des_lat; var origin_long = array[inputi].des_long; var departure_time = 'now'; var options = { host: 'maps.googleapis.com', path: '/maps/api/distancematrix/json?origins='+ origin_lat +','+origin_long+ '&destinations=' + office_lat + ',' + office_long + '&mode=TRANSIT&departure_time=1399399424&language=en-US&sensor=false' } http.get(options).on('response',function(response){ var data = ''; response.on('data',function(chunk){ data += chunk; }); response.on('end',function(){ var json = JSON.parse(data); console.log(json); var ttltimereturnoffice = json.rows[0].elements[0].duration.text; //var node = new Node(array[i],null, triptime,0,ttltimereturnoffice,false); //tripbylvtime.push(node); cb(ttltimereturnoffice + '\t' + inputi); }); }); } 

你不能在循环中检查结果。 循环在过去,callback发生在未来 – 你不能改变这一点。 你只能做两件事,一件是另一件的抽象:

1)您可以创buildcallback方式,以便收集结果并在全部出现时进行比较。

2)你可以使用promise来做同样的事情。

#1方法看起来像这样(在适当的时候修改代码中的cb调用):

 var results = []; function cb(index, ttltimereturnoffice) { results.push([index, ttltimereturnoffice]); if (results.length == array.length) { // we have all the results; find the best one, display, do whatever } } 

我不太清楚你正在使用什么库,如果它支持承诺,但是如果http.get返回一个承诺,你可以通过将承诺收集到一个数组中,然后使用承诺库的allwhen或类似附加一个callback所有正在做的事情。