From 4e0367a3e788f6a5a7b5e5d190ce5ba17f2a74b6 Mon Sep 17 00:00:00 2001
From: Christoph Reiter <reiter.christoph@gmail.com>
Date: Tue, 23 Mar 2021 12:46:33 +0100
Subject: [PATCH] Add an async/await variant for JSONLD.getInstance()

In theory this can replace all other API.
---
 packages/common/jsonld.js | 32 +++++++++++++++++++++++++-------
 1 file changed, 25 insertions(+), 7 deletions(-)

diff --git a/packages/common/jsonld.js b/packages/common/jsonld.js
index 69628958..956cbae2 100644
--- a/packages/common/jsonld.js
+++ b/packages/common/jsonld.js
@@ -16,6 +16,23 @@ export default class JSONLD {
         this.idToEntityNameMatchList = idToEntityNameMatchList;
     }
 
+    static async getInstance(apiUrl, lang = 'de') {
+        let promise = JSONLD.promises[apiUrl];
+        if (promise === undefined) {
+            JSONLD.doInitializationOnce(apiUrl);
+            promise = new Promise((resolve, reject) => {
+                JSONLD.initialize(
+                    apiUrl,
+                    (instance) => resolve(instance),
+                    (error) => reject(error),
+                    lang
+                );
+            });
+            JSONLD.promises[apiUrl] = promise;
+        }
+        return promise;
+    }
+
     static initialize(apiUrl, successFnc, failureFnc, lang = 'de') {
         if (lang !== 'de') {
             i18n.changeLanguage(lang);
@@ -51,11 +68,11 @@ export default class JSONLD {
         }
 
         JSONLD.initStarted[apiUrl] = true;
-        JSONLD.doInitialization(apiUrl);
+        JSONLD._doInitialization(apiUrl);
         // console.log("doInitializationOnce Done", apiUrl);
     }
 
-    static doInitialization(apiUrl) {
+    static _doInitialization(apiUrl) {
         const xhr = new XMLHttpRequest();
         xhr.open("GET", apiUrl, true);
 
@@ -156,7 +173,11 @@ export default class JSONLD {
      */
     static executeFailureFunctions(apiUrl, message = "") {
         if (JSONLD.failureFunctions[apiUrl] !== undefined) {
-            for (const fnc of JSONLD.failureFunctions[apiUrl]) if (typeof fnc == 'function') fnc();
+            for (const fnc of JSONLD.failureFunctions[apiUrl]) {
+                if (typeof fnc == 'function') {
+                    fnc(new Error(message));
+                }
+            }
         }
         JSONLD.failureFunctions[apiUrl] = [];
 
@@ -169,10 +190,6 @@ export default class JSONLD {
         }
     }
 
-    static getInstance(apiUrl) {
-        return JSONLD.instances[apiUrl];
-    }
-
     getEntityForIdentifier(identifier) {
         let entityName = this.getEntityNameForIdentifier(identifier);
         return this.getEntityForEntityName(entityName);
@@ -286,3 +303,4 @@ JSONLD.instances = {};
 JSONLD.successFunctions = {};
 JSONLD.failureFunctions = {};
 JSONLD.initStarted = {};
+JSONLD.promises = {};
-- 
GitLab