Promise
public struct Promise<Value>
A promise to provide a result later.
This is the provider API for Future<Value>
. If you want to return a Future<Value>
, you can use
the global functions promise()
, or create a new Promise<Value>
to fulfill in an asynchronous fashion.
To create a new promise, returning a Future<Value>
, follow this pattern:
promise {
"Hello World!"
}
The above function will return a Future<String>
eventually carrying the stirng Hello World!
.
You can also provide a future using a callback, like so:
promise(String.self) { completion in
... if success ...
completion(.fulfilled("Hello World!"))
... if error ...
completion(.rejected(error))
}
If you want to provide a Future<Value>
in a completely custom manner, you can create a pending promise, resolve it
when convenient, and flatMap return its Future
:
func someAsynOperation(args) -> Future<ResultType> {
let promise = Promise<ResultType>()
dispatchQueue.async {
... if success ...
promise.fulfill(value)
... if error ...
promise.reject(error)
}
return promise.future
}
-
The future value of this promise.
Declaration
Swift
public let future: Future<Value>
-
Creates a new pending
Promise
.Declaration
Swift
public init()
-
Fullfills the promise, setting a value to this promise’s
Future
Declaration
Swift
func fulfill(_ value: Value)
Parameters
value
Value to fulfill with
-
Rejects the promise, setting an error to this promise’s
Future
Declaration
Swift
func reject(_ error: Error)
Parameters
error
Error to reject with
-
Resolves the promise, setting either a value or an error to this promise’s
Future
Declaration
Swift
func resolve(_ result: Result<Value, Error>)
Parameters
result
Result<Value, Error>
to resolve with
-
Undocumented
Declaration
Swift
func fulfill()