[Pas2js] JS Sync/Async Limitations

Michael Van Canneyt michael at freepascal.org
Sat Feb 23 07:51:56 CET 2019



On Fri, 22 Feb 2019, warleyalex via Pas2js wrote:

> 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.

As said, I think we can have this.

Await and Async are just syntactic sugar for working with promises. 
Javascript gets away with it because it knows no types.

But this is Pascal; not Javascript. We have type safety to consider.

So there are some issues.

The async will be easy. As this is pascal, it will be a modifier:

function something() : TJSPromise; async;

The compiler should check the declared result type.

But in the case of an async function, you can return whatever you want, the JS
engine will wrap it in a promise. That means the compiler should not check
the Result type when you exit:

Result:=MyVeryNiceResult;

Now the compiler checks that MyVeryNiceResult is of the declared type
(TJSPromise). In the case of async, it should not do this.


for await, it is more difficult. Await takes a promise and 
returns whatever it resolves to, which is impossible to construct in Pascal.

The closest we can get to this is to make it a compiler intrinsic function,
much like exit, break or continue :

function await(aPromise : TJSPromise) : JSValue;

The compiler can check whether the encompassing function has async() in it.

So, I think it is possible to offer Async/Await in a pascal manner, but
there are some technicalities to consider.

Michael.


More information about the Pas2js mailing list