From f24a1aea8f508356bb51ed6972e0724dc36c9596 Mon Sep 17 00:00:00 2001 From: "Chris J. Shull" Date: Fri, 26 Apr 2024 13:48:08 -0700 Subject: [PATCH] Fix: Fix a timing issue for sequential importLibrary calls (#843) https://github.com/googlemaps/js-api-loader/issues/809 Fixes #809 --- src/index.test.ts | 17 +++++++++++++++++ src/index.ts | 16 ++++++++-------- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/index.test.ts b/src/index.test.ts index 7ccc942d..3fd017d8 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -425,6 +425,23 @@ test("importLibrary resolves correctly", async () => { expect(core).toEqual({ core: "fake" }); }); +test("importLibrary resolves correctly without warning with sequential await", async () => { + console.warn = jest.fn(); + window.google = { maps: {} } as any; + google.maps.importLibrary = async (name) => { + google.maps.version = "3.*.*"; + return { [name]: "fake" } as any; + }; + + const loader = new Loader({ apiKey: "foo" }); + const core = await loader.importLibrary("core"); + const marker = await loader.importLibrary("marker"); + + expect(console.warn).toHaveBeenCalledTimes(0); + expect(core).toEqual({ core: "fake" }); + expect(marker).toEqual({ marker: "fake" }); +}); + test("importLibrary can also set up bootstrap libraries (if bootstrap libraries empty)", async () => { const loader = new Loader({ apiKey: "foo" }); loader.importLibrary("marker"); diff --git a/src/index.ts b/src/index.ts index 546f5c15..a1f91d5a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -623,26 +623,26 @@ export class Loader { private execute(): void { this.resetIfRetryingFailed(); + if (this.loading) { + // do nothing but wait + return; + } + if (this.done) { this.callback(); } else { // short circuit and warn if google.maps is already loaded if (window.google && window.google.maps && window.google.maps.version) { console.warn( - "Google Maps already loaded outside @googlemaps/js-api-loader." + + "Google Maps already loaded outside @googlemaps/js-api-loader. " + "This may result in undesirable behavior as options and script parameters may not match." ); this.callback(); return; } - if (this.loading) { - // do nothing but wait - } else { - this.loading = true; - - this.setScript(); - } + this.loading = true; + this.setScript(); } } }