gnh1201 / welsonjs

WelsonJS - Build a Windows app on the Windows built-in JavaScript engine

Home Page:https://catswords.social/@catswords_oss

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[lib/std] AsyncFunction counter implementation

gnh1201 opened this issue · comments

There is no way to count the number of asynchronous jobs that are not currently completed. We need to implement a counter for asynchronous jobs.

lib/std.js

function AsyncFunction(f) {
    this.htmlfile = null;
    this.proxyWindow = null;
    this.f = f;

    this.run = function() {
+        AsyncFunction.counter++;    // increase number of async functions
+
+        var _this = this;
+        var f = function() {
+            _this.f();
+            AsyncFunction.counter--;    // decrease number of async functions
+        };

        if (this.proxyWindow != null) {
            try {
-                this.proxyWindow.setTimeout(1, this.f);
+                this.proxyWindow.setTimeout(1, f);
            } catch (e) {
                console.warn("AsyncFunction proxyWindow.setTimeout failed:", e.message);
-                sleep(1, this.f);
+                sleep(1, f);
            }
        } else {
-            sleep(1, this.f);
+            sleep(1, f);
        }
    };

    this.runSynchronously = function() {
        return this.f.apply(null, arguments);
    };

    // https://qiita.com/abcang/items/80b5733b5a96eeff9945
    if (typeof WScript !== "undefined") {
        try {
            this.htmlfile = CreateObject("htmlfile");
            this.proxyWindow = this.htmlfile.parentWindow;
        } catch (e) {
            console.warn("AsyncFunction require HTMLFILE object in WScript");
        }
    }
};
+AsyncFunction.counter = 0;    // static variable