javascript - 循环javascript Node js中的异步函数

标签 javascript json node.js google-maps httprequest

我需要扫描行程数组并计算当前行程与数组中每个行程之间的行程时间,并选择最短的一个。为了进行计算,我需要发送谷歌地图 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 收集到一个数组中来执行 #2,然后使用 Promise 库的 allwhen 或类似的方法在所有正在完成的 get 上附加回调。

关于javascript - 循环javascript Node js中的异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31442083/

相关文章:

json - 发布字符串会导致 Express 主体解析器抛出 SyntaxError

node.js - 获取数据库插入错误

Javascript 将 onload 附加到弹出窗口

json - 如何在Azure函数中引用json文件

javascript - 使用 CSS 突出显示当前页面上的导航选项卡?

json - 如何缩短类中变量的声明?

javascript - 客户端和服务器端 javascript 中 'this' 值的差异

node.js - 集合显示但文档未显示在 mongoDB 中

javascript - 如何构建大型 meteor.js 应用程序?

javascript - Node JS ctrl + C 不会停止服务器(使用 "npm start"启动服务器后)