我正在使用Google Maps Api。我有两个异步事件,库API调用和页面用户的位置请求。在geolocate() function
与getCurrentPosition
我检索用户的坐标,这个函数返回一个承诺在解决状态,如果一切正常,丝毫的位置value
。要加载API库,我使用JSONP,并在其中动态添加了脚本loadGoogleAPI()
,当库准备就绪时,将调用回调函数googleAPILoaded
。当上述2个异步事件发生时,我必须继续执行“异步执行”,并且在useGoogleMapsApi() function
(await Promise.all
)中使用了并行执行的模式。我的问题是,当我打电话Promise.all
,Promise.all
为googleAPIStatus
绑定到其初始值new 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);
}
}
您可以公开结算,googleAPIStatus
Promise
因此您可以结算googleAPILoaded
回调中的状态。
let resolve, reject;
let googleAPIStatus = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
function googleAPILoaded() {
console.log('loaded');
resolve()
}
setTimeout(googleAPILoaded, 100);
googleAPIStatus.then(() => console.log("resolved"))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句