Promises in D

Vladimir Panteleev thecybershadow.lists at gmail.com
Wed Apr 7 06:51:12 UTC 2021


On Wednesday, 7 April 2021 at 06:41:36 UTC, Vladimir Panteleev 
wrote:
> Hi,
>
> [...]

Sorry, I sent this too soon.

Going even lower, there are callbacks/delegates. In JavaScript, 
there are few reasons to use callbacks today, because they are 
much less composable and don't provide much other benefit. 
However, there is one reason in D where callbacks trump both 
fibers and promises: a callback's caller controls the lifetime of 
the passed values, whereas promises require that their held value 
either is owned by the promise, or has infinite lifetime (i.e. is 
immutable and on the heap). So, if you were to write a low-level 
high-performance networking library, you would probably want to 
have:

     void delegate(const(ubyte)[] bytes) onDataReceived;

where `bytes` is owned by the caller and is only valid until 
`onDataReceived` returns. You can't do the same with promises, 
because promises may be `then`'d at any point in the future, and 
you can't really do this with fibers because `await` returns its 
value as an lvalue and the network library doesn't know how long 
the user program needs the buffer for. (In case of fibers, you 
could instead do `ubyte[4096] buf; auto bytes = 
socket.receive(buf[]);`, but that's less flexible and may involve 
an additional copy.)

I see that eventcore uses delegates, which is probably the right 
choice considering the above.

In any case, here is the code that inspired me to write the 
promises module:

https://github.com/CyberShadow/ae/blob/ab6cb48e338047c5a30da7af7eeba122181ba1cd/demo/x11/demo.d#L76-L86

(Some good old callback hell.)

Here is the version with promises:

https://github.com/CyberShadow/ae/blob/3400e45bc14d93de381136a03b3db2dac7f56785/demo/x11/demo.d#L82-L88

Much better, but would be even nicer with fibers. :)



More information about the Digitalmars-d mailing list