10

Is there something like Scala's Promise in F#?

While futures are defined as a type of read-only placeholder object created for a result which doesn’t yet exist, a promise can be thought of as a writeable, single-assignment container, which completes a future. That is, a promise can be used to successfully complete a future with a value (by “completing” the promise) using the success method. Conversely, a promise can also be used to complete a future with an exception, by failing the promise, using the failure method.

The Async stuff covers part of this, but if you've got code that works outside the Async environment, Promises are a handy tool. (You can do things like complete a Promise in a UI thread, for example - even when the UI environment knows nothing at all about Async.)

1 Answer 1

14

The .Net equivalent of a promise is a TaskCompletionSource, so you can use them from F#. You can create an Async<T> from a Task<T> using Async.AwaitTask e.g.

let tcs = new TaskCompletionSource<int>()
let ta: Async<int> = Async.AwaitTask tcs.Task

//complete completion source using `SetResult`\`SetException` etc.

Not the answer you're looking for? Browse other questions tagged or ask your own question.