Skip to content

Web (HTTP/HTTPS) functions

When JavaScript is run inside of a browser, you can use the (non-ECMA) fetch function to perform http/https operations. The problem with fetch, though, is that it’s designed to run inside of an environment (the web browser) that’s totally asynchronous by definition. You start fetching something, then the browser goes on to do something else, and when (if ever) the fetched content becomes available, the execution cycle of the fetch operation is resumed. This works well in a browser, but would never work inside of a scripting environment where certainty is an absolute requirement when it comes to execution flow.

We have, therefore, added to SyncJS our own native http/https client object, called HttpCli.

It runs fully synchronized with the execution environment, ensuring that all functions that rely on the availability of the results of a web request will be correctly serialized. And, for convenience and ease of use, it is possible to configure it using the “fluent paradigm” (if you so wish).

Here below are three versions of the same example. The first one is more traditional, the second and third versions use the “fluent paradigm”.

First example (old-school, non-fluent)

ts
{
  var hc = new HttpCli();
  hc.Url("https://www.example.com");
  hc.Timeout(30);
  hc.Header("Custom-Header", "My custom header content");
  var res = hc.Get();
}

Second exmaple (fluent)

ts
{
  var hc = new HttpCli();
  var res = hc.Url("https://www.example.com").Timeout(30).Header("Custom-Header", "My custom header content").Get();
}

Third version (fluent and folded)

ts
{
  var hc = new HttpCli();
  var res = hc.Url("https://www.example.com").
               Timeout(30).
               Header("Custom-Header", "My custom header content").
               Get();
}