[Pas2js] JS Sync/Async Limitations

warleyalex warleyalex at yahoo.com.br
Sat Feb 23 04:48:05 CET 2019


Sergei Vertiev wrote
> Hello, warleyalex!
> I sure know about async functions and try this as "asm" stuff in my code.
> Do you know, that when you call "async" function this returns
> immidiatelly?
> so:
> 
> ---------------------------------------------
> async function r() {
>   var r2 = await fetch('https://jsonplaceholder.typicode.com/posts/1');
>   var j = await r2.json();
>   console.log("RESULT:"+j);
> };
> r();
> console.log("FINISH");
> ---------------------------------------------
> Console output will be:
> 
> FINSIH
> RESULT:xxxxxxxx

sync/await allows us to program using asynchronous requests in a
"synchronous" manner.
but to make it work, you need to wrap it inside an async function! (We need
to add the async keyword before the function declaration).

look the example:
--------------------
async function r() {
  var r2 = await fetch('https://jsonplaceholder.typicode.com/posts/1');
  var j = await r2.json();
  console.log(j);
};
r();
--------------------
In the 1st line, we make a GET request to
https://jsonplaceholder.typicode.com/posts/1 
Instead of continuing to the next line, we wait for the request to finish,
hence "await". 
When it finishes, it passes the resolved value to the r2 variable.
In the 2nd line, we get the JSON version of the r2. Again, we use await so
we can wait for it to complete (or fail) 
and then pass the result to the j variable.
Finally, in the last line, we log the value of the j variable to the
console.


look this following procedure:

procedure main;
begin
  Sleep(5000);
  console.log('A');
  Sleep(5000);
  console.log('B');
end;

when we run this code, it will immediately output 'A' and 'B'.
but I want our program to log 'A' after 5 seconds then log 'B' after 5
seconds...
that why we, we need the await keyword. In a "synchronous" manner.

I need to edit the emitted JS. I need to to wrap it inside an async function
and add "await" before the method "Sleep".

this.main = async function () {    
    await $mod.Sleep(5000);
    console.log('A');
    await $mod.Sleep(5000);
    console.log('B');
  };

when we run this method: $mod.main();

We are using the Sleep method in a "synchronous" manner.

That is why I think pas2js should have the await/async keywords.


==============================
SysUtils | Sleep method:
==============================
function Sleep(ms: NativeInt): TJSPromise;
begin
  Result := TJSPromise.New(
    procedure(resolve,reject : TJSPromiseResolver)
    begin
      window.setTimeout(
      procedure()
      begin
        console.log('Done waiting');
        resolve(ms);
      end, ms);
    end);
end;      
==========




--
Sent from: http://pas2js.38893.n8.nabble.com/


More information about the Pas2js mailing list