Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an F# equivalent to Scala's Promise?

Tags:

promise

scala

f#

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

like image 997
James Moore Avatar asked Jul 22 '13 17:07

James Moore


1 Answers

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.
like image 78
Lee Avatar answered Oct 22 '22 09:10

Lee