Asynchronous Computing with JavaScript Promises

markmmiller09
Kilo Expert

ECMA-262 (6th edition) supports promises natively. It is my understanding that ServiceNow uses Mozilla Rhino which is still on ECMA 5. Is there currently any sort of support for promises within the ServiceNow environment?

A simple use case is as follows: I have a large job, Job A, that currently takes around 5 minutes to finish execution. In a Script Include, I am looking to start Job A via a web service. I'd like to use a promise within the Script Include stating, once Job A has completed successfully, run this code. If it fails, run this code, etc. Are there any API's out there that support this type of behavior?

8 REPLIES 8

Hi,

See below onLoad client script mimicking promise (tested and working on Rome instance):

function onLoad() {
    function promiseFunction() {
        return new Promise(function(resolve, reject) {
            var state = g_form.getValue('state');
            setTimeout(function() {
                if (state === '2') {
                    reject(new Error('Promise rejected!'));
                }
                resolve("Promise resolved!")
            }, 3000);
        });
    }

    promiseFunction().then(function(result) {
        console.log('[AK] promise resolved: ' + result);
    }, function(err) {
        console.log('[AK] got error: ' + err);
    });

}

j_15
Tera Expert

Promises aren't actually available on the server side, although they will be available in Widgets and UI Builder scripts because those run on the browser's ES engine.

You can hack together some async behavior using gs.sleep() in non-scope applications, and there's a work-around for using it in scoped applications.

The issue I was having that led me to this question ended up having to do nothing with async execution. I was instantiating an instance of a class twice and the instance object's properties were somehow interfering with one another. It turns out I was instantiating another class on the prototype rather than in the initialize() method. This would mean that each instantiation of the class would still use the same reference on its (shared) prototype. Moving it to the initialize() method solved the issue.

I've implemented promises for server side code. await/async keywords wont work, but still...

https://www.servicenow.com/community/developer-articles/lib-async-true-server-side-concurrency-gt-pr...

 

 

var firstPromise = new x_424426_async.snPromise(function (resolve, reject) {
  gs.info("first promise");
  x_424426_async.setTimeout(function () {
    resolve("hello");
  }, 10000);
});

var secondPromise = new x_424426_async.snPromise(function (resolve, reject) {
  gs.info("second promise");
  resolve("world");
});

x_424426_async.snPromise.all([firstPromise, secondPromise]).then(function (results) {
  gs.info("promise result: " + results.join(","));
});

 

 

 https://github.com/kr4uzi/ServiceNow-LibAsync

fkiefl
Tera Contributor