javascript - 如何在 NodeJS 的循环内处理多个 Google Places API 请求?
问题描述
我有一个循环来分析一长串 GPS 点,然后根据需要选择一些点。
对于每个 GPS 点,我想找到周围的地方。
如何确保将每个响应与其他响应分开?
这是循环内的代码,当我有 1 个 GPS 点时它可以工作,但如果有更多则不是:
循环 GPS 路径,保存在哈希表中:
for (let indexI = 0; indexI < path_hash.length; indexI++) {
for (let indexJ = 0; indexJ < path_hash[indexI].length - 2; indexJ++) {
...
准备 URL 请求:
location = path_hash[indexI][indexJ].data.coords.latitude + "," + path_hash[indexI][indexJ].data.coords.longitude;
var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?" + "key=" + key + "&location=" + location + "&radius=" + radius + "&sensor=" + sensor + "&types=" + types + "&keyword=" + keyword;
...
执行请求:
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);
})
解决方案
使用您的功能,您可以这样做
// Turn the callback function into a Promise
const fetchUrl = (url) => {
return new Promise((resolve, reject) => {
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;
resolve(locations) // locations is returned by the Promise
});
}).on('error', function (e) {
console.log("Got error: " + e.message);
reject(e); // Something went wrong, reject the Promise
});
});
}
// Loop the GPS path, saved in hash table
...
// Prepare the urls
...
const GPSPoints = [
'url1',
'url2',
...
];
// Fetch the locations for all the GPS points
const promises = GPSPoints.map(point => fetchUrl(point));
// Execute the then section when all the Promises have resolved
// which is when all the locations have been retrieved from google API
Promise.all(promises).then(all_locations => {
console.log(all_locations[0]); // Contains locations for url1
console.log(all_locations[1]); // Contains locations for url2
...
});
推荐阅读
- flutter - Flutter Appbar 动作调用子类函数
- r - 使用 ggplot2 创建列表图
- ruby-on-rails - NGINX 没有在生产中使用 Ruby on rails + Docker 捕获请求
- mongodb - 如何反转 MongoDB 聚合结果?
- yii - 模型关系图/数据库关系图
- java - 我们如何在 selenium webdriver java 中从 DB 中获取 OTP
- python - Blockly Python 端口
- python - 简单的公共 API 调用上的 SSLError
- java - 无法将 TextView 放在 Java 中的 Google Vision Scanner 视图下
- reactjs - 运行 ReactJS/TailwindCSS/Heroku 时出错:React Refresh 运行时不应包含在生产包中