简体   繁体   中英

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

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

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 eg

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM