Javascript 如何在NodeJS中处理循环内的多Google Places API请求?

Javascript 如何在NodeJS中处理循环内的多Google Places API请求?,javascript,asynchronous,promise,nodes,google-places-api,Javascript,Asynchronous,Promise,Nodes,Google Places Api,我有一个回路,可以分析一长串GPS点,然后根据需要选择一些点。 对于每个GPS点,我想找到周围的位置 如何确保每个响应与其他响应分开 以下是循环中的代码,当我有1个GPS点时,它可以工作,但如果有更多GPS点,则不能工作: 循环GPS路径,保存在哈希表中: for (let indexI = 0; indexI < path_hash.length; indexI++) { for (let indexJ = 0; indexJ < path_hash[indexI].len

我有一个回路,可以分析一长串GPS点,然后根据需要选择一些点。
对于每个GPS点,我想找到周围的位置

如何确保每个响应与其他响应分开

以下是循环中的代码,当我有1个GPS点时,它可以工作,但如果有更多GPS点,则不能工作:

循环GPS路径,保存在哈希表中:

for (let indexI = 0; indexI < path_hash.length; indexI++) {
    for (let indexJ = 0; indexJ < path_hash[indexI].length - 2; indexJ++) {

执行请求:

https.get(url, function (response) {
    var body = '';
    response.on('data', function (chunk) {
        body += chunk;
    });

    response.on('end', function () {
        var places = places + JSON.parse(body);
        var locations = places.results;
        console.log(locations);
    });

}).on('error', function (e) {
    console.log("Got error: " + e.message);
})  

使用你的功能,你可以这样做

//将回调函数转换为承诺
常量fetchUrl=(url)=>{
返回新承诺((解决、拒绝)=>{
https.get(url、函数(响应){
变量体=“”;
响应.on('data',函数(块){
body+=块;
});
response.on('end',function(){
var places=places+JSON.parse(body);
变量位置=位置。结果;
resolve(locations)//承诺返回位置
});
}).on('error',函数(e){
log(“获取错误:+e.message”);
拒绝(e);//出了问题,拒绝承诺
});
});
}
//循环GPS路径,保存在哈希表中
...
//准备URL
...
常数GPSPoints=[
“url1”,
“url2”,
...
];
//获取所有GPS点的位置
const promises=GPSPoints.map(point=>fetchUrl(point));
//当所有承诺都已解决时,执行then部分
//这就是从谷歌API检索所有位置的时间
承诺。所有(承诺)。然后(所有位置=>{
log(所有_位置[0]);//包含url1的位置
log(所有_位置[1]);//包含url2的位置
...
});

每个点是否有不同的
url
s?(就像一个点列表)。请分享更多的上下文代码(如位置列表的启动以及构建
url
)的方式)@iuliu.net立即检查。删除位置列表这是一次处理多个请求的尝试。你能帮助理解上面的代码中哪些应该在循环之外吗?你想让我包括生成URL的部分吗?想知道何时调用Promise.all(promises)。然后。。?循环完成后?我编辑了上面的代码,添加了gps路径和URL的构建位置。关于这段代码
Promise.all(promises)。然后(callback)
promises
是一个
Promise
数组。如果您不熟悉这个概念,下面是Eric Elliot的一篇很棒的文章:。
Promise
是处理异步代码的对象。它代表了一个可能现在、将来或永远都可用的值。如果希望在承诺生成值后执行一段代码,可以使用其
then(callback)
函数<生成值时将调用代码>回调
https.get(url, function (response) {
    var body = '';
    response.on('data', function (chunk) {
        body += chunk;
    });

    response.on('end', function () {
        var places = places + JSON.parse(body);
        var locations = places.results;
        console.log(locations);
    });

}).on('error', function (e) {
    console.log("Got error: " + e.message);
})