logo

NJP

Lib Async: True Server Side Concurrency -> Promises, Tasks, "setTimeout" and more

Import · Aug 13, 2023 · article

Since I started using ServiceNow a few years ago, I was always missing concurrency features like client-side Promises, or C#-like Task - even a basic setTimeout would be sufficient.

A can proudly say, that this search is finally over - introducing "Lib Async":

gs.info("This will execute first");
x_424426_async.setTimeout(function () {
  gs.info("This will execute third (after a second wait time)");
}, 1000);
gs.info("This will execute second");

Background Script Output:

MarkusKraus_0-1691937099722.png

Log Output:

MarkusKraus_1-1691937209084.png

More Complex Showcase with Promises:

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(","));
})

Background Script Output:

Note that we do not get a result right away because the first promise is resolved after ten second

MarkusKraus_2-1691937392960.png

System Log Output:

Notice the ten second difference between the outputs

MarkusKraus_4-1691937570205.png

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

View original source

https://www.servicenow.com/community/developer-articles/lib-async-true-server-side-concurrency-gt-promises-tasks-quot/ta-p/2642027