Promises in D

Vladimir Panteleev thecybershadow.lists at gmail.com
Wed Apr 7 06:41:36 UTC 2021


Hi,

Here is an implementation of promises in D:

https://github.com/cybershadow/ae/blob/next/utils/promise.d

Docs: https://ae.dpldocs.info/ae.utils.promise.Promise.html

It attempts to implement the Promises/A+ standard as closely as 
possible.

Some thoughts about promises in D:

JavaScript's path towards asynchronous programming was callbacks 
-> promises -> async/await. Promises in JavaScript are one of the 
basic building blocks (and the next step down in terms of 
lowering) of async/await: `async` functions transparently return 
a promise, and `await` accepts a promise and "synchronously" 
waits for it to resolve, converting failures into thrown 
exceptions.

D doesn't have async/await (and, probably adding it would require 
a *significant* amount of work in the compiler), but D does have 
fibers. An interesting observation is that the same principles of 
async/await and promise interaction also apply to fibers: a task 
running in a fiber can be represented as a promise, and, in the 
fiber world, `await` is just a simple function which yields the 
fiber and wakes it up when the promise resolves (also converting 
failures into thrown exceptions).

Fibers do have overhead in terms of requiring the stack 
allocation per task and the cost of context switching, so they 
may not be the best solution all of the time. So, although an 
asynchronous networking / event loop library could just build 
everything on fibers (as older versions of Vibe.d have), it would 
seem that you could instead use promises as the lower-overhead 
"glue", and make fibers opt-in.




More information about the Digitalmars-d mailing list