需要等待 Google API 但睡眠功能不起作用

Need to wait for Google API but sleep function doesn't work

我需要在我的 svelte 项目中加载 Google 地图 API。 我正在使用 js-api-loader npm 包。

这是我用来加载 Google API:

的简单代码

loader.js

import { Loader } from '@googlemaps/js-api-loader';

let googleIsLoaded = false;

async function loadGoogleMapsAPI() { 
  if (!googleIsLoaded) {
    const libraries = ['places'];
    try {
      const loader = new Loader({
        apiKey: API_KEY,
        version: 'weekly',
        libraries,
      });
      console.info('Loading Google API ...'); // LOGGED 1st -> OK
      await loader.load();
      console.info('Google API is loaded'); // LOGGED 6th -> KO
      googleIsLoaded = true;
    } catch (error) {
      throw new Error(`Google API Loader failed ${error.message}`);
    }
  }
}

当页面加载时,它首先点击下面定义的路由 route/index.svelte:

<script context="module">
  export const ssr = false;
</script>

<script>
  import MyComp from '$components/MyComp.svelte';
  import { loadGoogleMapsAPI } from '$lib/loader.js';

  init();

  async function init() {
    try {
      await loadGoogleMapsAPI();
    } catch (e) {
      console.error(e);
    }
  }

  <MyComp />

然后,下面的MyComp.svelte加载:

import { onMount } from 'svelte';

let google;
onMount(() => {
    console.log('mounted'); // LOGGED 2nd -> OK
    google = window.google;
    if (google === undefined) {
      console.log('google is undefined'); // LOGGED 3rd -> OK
      sleep(5000, init());
    } else {
      console.log('google is defined');
    }
});

async function init() {
    ...
    autocompleteWidget = new google.maps.places.Autocomplete(input, options); 
/////////// LOGGED 5th -> KO: EXCEPTION GOOGLE IS NOT DEFINED /////////
}

这里是睡眠的辅助函数

helpers.js


export async function sleep(time, fn, ...args) {
  console.info('sleep ' + time + 'ms');  // LOGGED 4th -> OK
  await timeout(time);
  console.info('woken'); // LOGGED 7th -> KO
  return fn(...args);
}

function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

但是无论出于何种原因,都会触发 init() 函数而忽略 sleep(5000, init()) 调用:/

感谢您的帮助。

控制台

loader.js: Loading Google API ...
MyComp.svelte: mounted
MyComp.svelte: google is undefined
helpers.js: sleep 5000ms
MyComp.svelte:106 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'maps')
helpers.js: Google API is loaded
helpers.js: woken

您需要传递函数引用而不是调用它。

改变

sleep(5000, init());

至:

sleep(5000, init);