【发布时间】:2021-05-15 13:22:42
【问题描述】:
我正在使用谷歌地图 API。我有两个异步事件,库 API 调用和页面用户的位置请求。在geolocate() function 和getCurrentPosition 中,我检索用户的坐标,如果一切正常,此函数返回一个已解决状态的Promises,位置为value。为了加载 API 库,我使用 JSONP 并在 loadGoogleAPI() 中动态添加了一个脚本,当库准备就绪时,将调用回调函数 googleAPILoaded。当上述 2 个异步事件发生时,我必须继续“异步执行”,并且我正在使用 useGoogleMapsApi() function (await Promise.all) 中的并行执行模式。
我的问题是,当我调用 Promise.all 时,Promise.all 的 googleAPIStatus 绑定到其初始值 new Promise(()=>{}) 挂起的 Promise。当加载带有 JSONP 的库时,我将变量的值 googleAPIStatus=Promise.resolve() 更改为已解析的 Promise,但 Promise.all 仍然与初始待处理的 Promise 值相关。
这里是代码。我该如何解决?
let googleAPIStatus = new Promise(()=>{});
function googleAPILoaded(){
console.log('loaded');
googleAPIStatus = Promise.resolve();
}
function useGoogleMapsApi(){
loadGoogleAPI();//JSONP with a dynamic script
let [_,posizione]= await Promise.all([googleAPIStatus , geolocate()]); //parallel execution pattern
//Here if resolved either the Promises
}
function loadGoogleAPI(){
let isLibraryLoaded = document.querySelector("script[src='google-api']");
if(!(typeof google === 'object' && typeof google.maps === 'object')){
//Add dynamic script that load the library
let script = document.createElement('script');
script.type='text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?key=HEREMYKEY&libraries=places&callback=googleAPILoaded';
script.id = 'google-api';
if(!isLibraryLoaded)
document.body.appendChild(script);
else
isLibraryLoaded.parentNode.replaceChild(script,isLibraryLoaded);
}
}
【问题讨论】:
标签: javascript google-maps-api-3 async-await promise es6-promise