承诺挂起作为 gAPI 地理编码调用

问题描述

Google Api 地图的地方调用中,我还需要检索地方坐标:

function currentDateTime() {
        var x = new Date()
        var x1= x.getMonth() + 1+ "/" + x.getDate() + "/" + x.getFullYear(); 
        x1 = x1 + " - " +  x.getHours( )+ ":" +  x.getMinutes() + ":" +  x.getSeconds();
        document.getElementById('currentDateTime').innerHTML = x1;
        
         }

currentDateTime();

不幸的是,我得到了“PROMISE”值,而不是坐标字符串一。 我找不到返回和解开承诺的方法:(

你能帮我吗?

tyvm

解决方法

您的代码是异步的,并且无法使其同步,因此与其尝试返回 Promise 以外的其他内容,不如调整您的代码:

if (status != google.maps.places.PlacesServiceStatus.OK) {
  callback(data);
} else {
  var geocoder = new google.maps.Geocoder();
}

const coords = await Promise.all(
    predictions.map(x => geocoder.geocode({
        'placeId': x.place_id
      })).map(x => x.then(responses => {
        const lat = responses[0].geometry.location.lat()
        const lng = responses[0].geometry.location.lng()
        return (lat + '#' + lng)
      })).map(x => x.then(coords => ({
        value: coords
      }))));

data.results = predictions.map(({ place_id,description }) => ({ place_id,description })).map((x,i) => ({ ...x,...coords[i] }));

console.log(data.results);

免责声明:我没有测试它,所以它可能包含错误

注意:此代码意味着周围的函数被声明为 async,这意味着它也返回一个 Promise,因此您也必须调整其余代码。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...