From f788cf92219996630ff387fefa659bbfd963ceaf Mon Sep 17 00:00:00 2001 From: Brendan Early Date: Fri, 16 Aug 2024 00:20:04 -0500 Subject: [PATCH] add timeout to managed storage function --- src/models/storage.ts | 38 +++++++++++++++++++++++--------------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/src/models/storage.ts b/src/models/storage.ts index 05ab7718..431b72a1 100644 --- a/src/models/storage.ts +++ b/src/models/storage.ts @@ -691,23 +691,31 @@ export class ManagedStorage { static get(key: string): T | undefined; static get(key: string, defaultValue: T): T; static get(key: string, defaultValue?: T) { - return new Promise((resolve: (result: T | undefined) => void) => { - if (chrome.storage.managed) { - chrome.storage.managed.get((data) => { - if (chrome.runtime.lastError) { - return resolve(defaultValue); - } - if (data) { - if (data[key]) { - return resolve(data[key]); + const managedStoragePromise = new Promise( + (resolve: (result: T | undefined) => void) => { + if (chrome.storage.managed) { + chrome.storage.managed.get((data) => { + if (chrome.runtime.lastError) { + return resolve(defaultValue); } - } - return resolve(defaultValue); - }); - } else { - // no available in Safari - resolve(defaultValue); + if (data) { + if (data[key]) { + return resolve(data[key]); + } + } + return resolve(defaultValue); + }); + } else { + // no available in Safari + resolve(defaultValue); + } } + ); + + const timeoutPromise = new Promise((resolve) => { + setTimeout(() => resolve(defaultValue), 1500); }); + + return Promise.race([managedStoragePromise, timeoutPromise]); } }