Bladeren bron

♻️ prefer async/await

jmacura 4 jaren geleden
bovenliggende
commit
01c3cd7f3d
1 gewijzigde bestanden met toevoegingen van 86 en 89 verwijderingen
  1. 86 89
      src/adjuster/adjuster.service.ts

+ 86 - 89
src/adjuster/adjuster.service.ts

@@ -129,42 +129,53 @@ export class AdjusterService {
     });
   }
 
-  calculateClusters(): void {
+  async calculateClusters(): Promise<void> {
     this._clusteringInProcess = true;
-    this.httpClient
-      .post(this.serviceBaseUrl + 'eu/clusters/', {
-        numberOfClusters: this.numberOfClusters,
-        factors: this.factors.map((f) => {
-          return {
-            factor: f.name,
-            weight: f.weight,
-            datasets: f.datasets
-              .filter((ds) => ds.included)
-              .map((ds) => ds.name),
-          };
-        }),
-      })
-      .toPromise()
-      .then((data: any) => {
-        const clusterData = data.response;
-        // Store relation between region and its data in a hash-table-like structure
-        // more memory consuming, but much faster then find()
-        const codeRecordRelations = {};
-        clusterData.forEach((c) => {
-          codeRecordRelations[c['nuts_id'].toUpperCase()] = c;
-        });
-        console.time('forEach-Cluster');
-        /*const clusters = [];
+    let data: any;
+    try {
+      data = await this.httpClient
+        .post(this.serviceBaseUrl + 'eu/clusters/', {
+          numberOfClusters: this.numberOfClusters,
+          factors: this.factors.map((f) => {
+            return {
+              factor: f.name,
+              weight: f.weight,
+              datasets: f.datasets
+                .filter((ds) => ds.included)
+                .map((ds) => ds.name),
+            };
+          }),
+        })
+        .toPromise();
+    } catch (error) {
+      console.warn(`Error obtaining data from ${this.serviceBaseUrl}.`);
+      console.log(error);
+      this._clusteringInProcess = false;
+      this.adjusterEventService.loaded.next({
+        success: false,
+        type: 'clusters',
+        err: error,
+      });
+    }
+    const clusterData = data.response;
+    // Store relation between region and its data in a hash-table-like structure
+    // more memory consuming, but much faster then find()
+    const codeRecordRelations = {};
+    clusterData.forEach((c) => {
+      codeRecordRelations[c['nuts_id'].toUpperCase()] = c;
+    });
+    console.time('forEach-Cluster');
+    /*const clusters = [];
         for (const region of clusterData) {
           if (!clusters.includes(region[this.method])) {
             clusters.push(region[this.method]);
           }
         }*/
-        //for (const method of this.methods) {
-        this.attractivenessClustersService.processClusters(codeRecordRelations);
-        //}
-        console.timeEnd('forEach-Cluster');
-        /*let max = 0;
+    //for (const method of this.methods) {
+    this.attractivenessClustersService.processClusters(codeRecordRelations);
+    //}
+    console.timeEnd('forEach-Cluster');
+    /*let max = 0;
         this.clusters.forEach((a) => {
           if (a.aggregate > max) {
             max = a.aggregate;
@@ -177,71 +188,57 @@ export class AdjusterService {
         this.attractivity.forEach((a) => {
           this.nutsCodeRecordRelations[a.code] = a;
         });*/
-        // Fake the legend
-        nuts.nuts3ClustersSource.legend_categories = this.adjusterLegendService.createClusterLegend(
-          this.numberOfClusters
-        );
-        this._clustersLoaded = true;
-        this._clusteringInProcess = false;
-        this.adjusterEventService.loaded.next({
-          success: true,
-          type: 'clusters',
-        });
-      })
-      .catch((error) => {
-        console.warn(`Error obtaining data from ${this.serviceBaseUrl}.`);
-        console.log(error);
-        this._clusteringInProcess = false;
-        this.adjusterEventService.loaded.next({
-          success: false,
-          type: 'clusters',
-          err: error,
-        });
-      });
+    // Fake the legend
+    nuts.nuts3ClustersSource.legend_categories = this.adjusterLegendService.createClusterLegend(
+      this.numberOfClusters
+    );
+    this._clustersLoaded = true;
+    this._clusteringInProcess = false;
+    this.adjusterEventService.loaded.next({
+      success: true,
+      type: 'clusters',
+    });
   }
 
-  init(): void {
+  async init(): Promise<void> {
     this._loadInProcess = true;
-    this.httpClient
-      .get(this.serviceBaseUrl + 'eu/datasets/')
-      .toPromise()
-      .then((data: any) => {
-        this.factors = data.map((dataset) => {
+    let data: any;
+    try {
+      data = await this.httpClient
+        .get(this.serviceBaseUrl + 'eu/datasets/')
+        .toPromise();
+    } catch (error) {
+      console.warn(`Web service at ${this.serviceBaseUrl} unavailable!`);
+      console.log(error);
+      this._loadInProcess = false;
+      /*this.adjusterEventService.loaded.next({
+        success: false,
+        err: error,
+      });*/
+    }
+    this.factors = data.map((dataset) => {
+      return {
+        name: dataset.Factor,
+        weight: this.initialWeights[dataset.Factor] ?? 1,
+        datasets: [],
+      };
+    });
+    this.factors = this.hsUtilsService.removeDuplicates(this.factors, 'name');
+    this.factors.forEach((factor) => {
+      factor.datasets = data
+        .filter((ds) => ds.Factor === factor.name)
+        .map((ds) => {
           return {
-            name: dataset.Factor,
-            weight: this.initialWeights[dataset.Factor] ?? 1,
-            datasets: [],
+            name: ds.Name,
+            desc: ds.Description,
+            included: true,
           };
         });
-        this.factors = this.hsUtilsService.removeDuplicates(
-          this.factors,
-          'name'
-        );
-        this.factors.forEach((factor) => {
-          factor.datasets = data
-            .filter((ds) => ds.Factor === factor.name)
-            .map((ds) => {
-              return {
-                name: ds.Name,
-                desc: ds.Description,
-                included: true,
-              };
-            });
-        });
-        this._loadInProcess = false;
-        this.apply();
-        // In HSL 2.5, setting layer greyscale breaks the print() functionality
-        //this.hsLayerManagerService.setGreyscale(osmLayer);
-      })
-      .catch((error) => {
-        console.warn(`Web service at ${this.serviceBaseUrl} unavailable!`);
-        console.log(error);
-        this._loadInProcess = false;
-        /*this.adjusterEventService.loaded.next({
-          success: false,
-          err: error,
-        });*/
-      });
+    });
+    this._loadInProcess = false;
+    this.apply();
+    // In HSL 2.5, setting layer greyscale breaks the print() functionality
+    //this.hsLayerManagerService.setGreyscale(osmLayer);
   }
 
   clustersLoaded(): boolean {