Цепочка Promise + jQuery Ajax заставляет память расти. Я правильно их использую? - PullRequest
0 голосов
/ 08 марта 2020

У меня есть JS, который должен периодически выполнять удаленную операцию, а затем реагировать на нее. Вихревой поток:

- Start the operation in main script
  -> `setInterval` calling a function every 5 seconds
     -> This function waits for a `Promise` that internally...
        -> ... calls `$.ajax`, validate the response, then resolve or reject.

Я вижу рост памяти в моем приложении, и эта цепочка операций может быть причиной. Правильно ли я использую Promises?

Основная точка входа просто:

StateWatcher.startWatchSystem();

Тогда задействованные модули:

var StateWatcher = {

    // is called by the main app to start the backround check every 5 sec
    // the actual function that performs the update is "doSystemStateUpdate"
    startWatchSystem: function() {    
        this.doSystemStateUpdate();
        this.systemWatchTimeout = setInterval(() => {
            this.doSystemStateUpdate();
        }, 5000)
    },

    <...>

    // this is "doSystemStateUpdate": the remote call is performed by another module "RemoteQuery.getSystemState()".
    // that last function returns a Promise (see below), so I can check the result with "then" and "catch"
    doSystemStateUpdate: function() {
        RemoteQuery.getSystemState()
        .then((data) => {
            // ok, got the new State
            this.currentSystemState = data.Message;
            // ... inform other modules etc etc...
        })
        .catch((error) => {
            Logger.write("error", "doSystemStateUpdate:");
            Logger.write("error", error);
        });
    }
}

Вот "RemoteQuery" модуль:

var RemoteQuery = {

    connectionError: false,

    // the getSystemState internally calls jQuery AJAX but then enclose it in a Promise
    // When Ajax finishes, before actually resolve the promise it must do a quick check on the Ajax result, using function "validateResponse"
    getSystemState: function () { 
        return new Promise((resolve, reject) => {
            $.ajax({
                dataType: "json",
                url: <.... http...>,
                method: "GET",
                cache: false,
                success: function(data) { RemoteQuery.validateResponse(true, resolve, data) },
                error: function(xhr, opts, error) { RemoteQuery.validateResponse(false, reject, xhr) }
            });
        })
    }

    <...>

    // this is the last step: this function sets an "alarm" flag if the ajax operation was not ok.
    // at the end, it calls the function to resolve the promise
    validateResponse: function(ok, then, args) {
        if (this.connectionError == false && ok == false) {
            this.connectionError = true;
            // do other stuff (logging,...)
        }
        else if (this.connectionError == true && ok == true) {
            this.connectionError = false;
            // do other stuff (logging,...)
        }

        then(args); // now resolve or reject based on how it has been called after ajax->success or ajax->error
    },
}
...