我需要扫描行程数组并计算当前行程与数组中每个行程之间的行程时间,然后选择最短的行程。为了进行计算,我需要发送google maps api调用。我对异步回调函数非常困惑。谁能帮我这个问题,如何在for循环内发送api调用并检查结果并继续?谢谢。行程在我的数组列表中;数组: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); }); });} 最佳答案 您无法在循环中检查结果。循环在过去,回调在将来发生-您无法更改。您只能做两件事,一件事是另一件事的抽象:1)您可以以这样的方式创建您的回调:它将收集结果并在所有结果都存在时进行比较。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 }}我不太清楚您使用的是哪个库,并且它是否支持promise,但是如果http.get返回promise,则可以通过将promise收集到数组中,然后使用promise库的all或或类似名称,以在完成的所有when上附加回调。关于javascript - 循环JavaScript Node js中的异步函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31442083/