Promise
public struct Promise<Value, Error>
extension Promise: Equatable
A Promise is a construct that will eventually hold a value or error, and can invoke callbacks
when that happens.
Example usage:
Promise(on: .utility) { resolver in
let value = try someLongComputation()
resolver.fulfill(with: value)
}.then(on: main) { value in
self.updateUI(with: value)
}.catch(on: .main) { error in
self.handleError(error)
}
Promises can also be cancelled. With a Promise object you can invoke .requestCancel(), which
is merely advisory; the promise does not have to actually implement cancellation and may resolve
anyway. But if a promise does implement cancellation, it can then call resolver.cancel(). Note
that even if the promise supports cancellation, calling .requestCancel() on an unresolved
promise does not guarantee that it will cancel, as the promise may be in the process of
resolving when that method is invoked. Make sure to use the invalidation token support if you
need to ensure your registered callbacks aren’t invoked past a certain point.
Note
If a registered callback is invoked (or would have been invoked if no token was provided) it is guaranteed to be released on the context. This is important if the callback captures a value whose deallocation must occur on a specific thread (such as the main thread). If the callback is not invoked (ignoring tokens) it will be released on whatever thread the promise was resolved on. For example, if a promise is fulfilled, any callback registered with.then(on:token:_:) will be released on the context, but callbacks registered with
.catch(on:token:_:) will not. If you need to guarantee the thread that the callback is
released on, you should use .always(on:token:_:) or one of the .mapResult(on:token:_:)
variants.
-
Returns the result of the promise.
Once this value becomes non-
nilit will never change.Declaration
Swift
public var result: PromiseResult<Value, Error>? { get } -
Returns a
Promiseand aPromise.Resolverthat can be used to fulfill that promise.Note
In most cases you want to usePromise(on:_:)instead.Declaration
Swift
public static func makeWithResolver() -> (Promise<Value, Error>, Promise<Value, Error>.Resolver) -
Returns a new
Promisethat will be resolved using the given block.Declaration
Swift
public init(on context: PromiseContext, _ handler: @escaping (_ resolver: Resolver) -> Void)Parameters
contextThe context to execute the handler on.
handlerA block that is executed in order to fulfill the promise.
resolverThe
Resolverused to resolve the promise. -
Returns a
Promisethat is already fulfilled with the given value.Declaration
Swift
public init(fulfilled value: Value) -
Returns a
Promisethat is already rejected with the given error.Declaration
Swift
public init(rejected error: Error) -
Returns a
Promisethat is already resolved with the given result.Declaration
Swift
public init(with result: PromiseResult<Value, Error>) -
Registers a callback that is invoked when the promise is fulfilled.
Declaration
Swift
public func then(on context: PromiseContext = .auto, token: PromiseInvalidationToken? = nil, _ onSuccess: @escaping (Value) -> Void) -> Promise<Value, Error>Parameters
contextThe context to invoke the callback on. If not provided, defaults to
.auto, which evaluates to.mainwhen invoked on the main thread, otherwise.default.tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonSuccessfrom being invoked.onSuccessThe callback that is invoked with the fulfilled value.
Return Value
A new promise that will resolve to the same value as the receiver. You may safely ignore this value.
-
Registers a callback that is invoked when the promise is fulfilled.
Declaration
Swift
public func map<U>(on context: PromiseContext, token: PromiseInvalidationToken? = nil, _ onSuccess: @escaping (Value) -> U) -> Promise<U, Error>Parameters
contextThe context to invoke the callback on.
tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonSuccessfrom being invoked. If the promise is fulfilled and the token is invalidated, the returned promise will be cancelled.onSuccessThe callback that is invoked with the fulfilled value.
Return Value
A new promise that will be fulfilled with the return value of
onSuccess. If the receiver is rejected or cancelled, the returned promise will also be rejected or cancelled. -
Registers a callback that is invoked when the promise is fulfilled.
Declaration
Swift
public func flatMap<U>(on context: PromiseContext, token: PromiseInvalidationToken? = nil, _ onSuccess: @escaping (Value) -> Promise<U, Error>) -> Promise<U, Error>Parameters
contextThe context to invoke the callback on.
tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonSuccessfrom being invoked. If the promise is fulfilled and the token is invalidated, the returned promise will be cancelled.onSuccessThe callback that is invoked with the fulfilled value.
Return Value
A new promise that will be eventually resolved using the promise returned from
onSuccess. If the receiver is rejected or cancelled, the returned promise will also be rejected or cancelled. -
Registers a callback that is invoked when the promise is rejected.
This method (or
always) should be used to terminate a promise chain.Declaration
Swift
@discardableResult public func `catch`(on context: PromiseContext = .auto, token: PromiseInvalidationToken? = nil, _ onError: @escaping (Error) -> Void) -> Promise<Value, Error>Parameters
contextThe context to invoke the callback on. If not provided, defaults to
.auto, which evaluates to.mainwhen invoked on the main thread, otherwise.default.tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonErrorfrom being invoked.onErrorThe callback that is invoked with the rejected error.
Return Value
A new promise that will resolve to the same value as the receiver. You may safely ignore this value.
-
Declaration
Swift
public func recover(on context: PromiseContext, token: PromiseInvalidationToken? = nil, _ onError: @escaping (Error) -> Value) -> Promise<Value, NoError>Parameters
contextThe context to invoke the callback on.
tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonErrorfrom being invoked. If the promise is rejected and the token is invalidated, the returned promise will be cancelled.onErrorThe callback that is invoked with the rejected error.
Return Value
A new promise that will be fulfilled with the return value of
onError. If the receiver is fulfilled or cancelled, the returned promise will also be fulfilled or cancelled. -
Declaration
Swift
public func mapError<E>(on context: PromiseContext, token: PromiseInvalidationToken? = nil, _ onError: @escaping (Error) -> E) -> Promise<Value, E>Parameters
contextThe context to invoke the callback on.
tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonErrorfrom being invoked. If the promise is rejected and the token is invalidated, the returned promise will be cancelled.onErrorThe callback that is invoked with the rejected error.
Return Value
A new promise that will be rejected with the return value of
onError. If the receiver is fulfilled or cancelled, the returned promise will also be fulfilled or cancelled. -
Declaration
Swift
public func flatMapError<E>(on context: PromiseContext, token: PromiseInvalidationToken? = nil, _ onError: @escaping (Error) -> Promise<Value, E>) -> Promise<Value, E>Parameters
contextThe context to invoke the callback on.
tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonErrorfrom being invoked. If the promise is rejected and the token is invalidated, the returned promise will be cancelled.onErrorThe callback that is invoked with the rejected error.
Return Value
A new promise that will be eventually resolved using the promise returned from
onError. If the receiver is fulfilled or cancelled, the returned promise will also be fulfilled or cancelled. -
Declaration
Swift
public func tryMapError<E>(on context: PromiseContext, token: PromiseInvalidationToken? = nil, _ onError: @escaping (Error) throws -> E) -> Promise<Value, Swift.Error> where E : ErrorParameters
contextThe context to invoke the callback on.
tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonErrorfrom being invoked. If the promise is rejected and the token is invalidated, the returned promise will be cancelled.onErrorThe callback that is invoked with the rejected error.
Return Value
A new promise that will be rejected with the return value of
onError, or is rejected ifonErrorthrows an error. If the receiver is fulfilled or cancelled, the returned promise will also be fulfilled or cancelled. -
Declaration
Swift
public func tryFlatMapError<E>(on context: PromiseContext, token: PromiseInvalidationToken? = nil, _ onError: @escaping (Error) throws -> Promise<Value, E>) -> Promise<Value, Swift.Error> where E : ErrorParameters
contextThe context to invoke the callback on.
tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonErrorfrom being invoked. If the promise is rejected and the token is invalidated, the returned promise will be cancelled.onErrorThe callback that is invoked with the rejected error.
Return Value
A new promise that will be eventually resolved using the promise returned from
onError, or is rejected ifonErrorthrows an error. If the receiver is fulfilled or cancelled, the returned promise will also be fulfilled or cancelled. -
-
-
Registers a callback that will be invoked with the promise result, no matter what it is.
Declaration
Swift
@discardableResult public func always(on context: PromiseContext = .auto, token: PromiseInvalidationToken? = nil, _ onComplete: @escaping (PromiseResult<Value, Error>) -> Void) -> Promise<Value, Error>Parameters
contextThe context to invoke the callback on. If not provided, defaults to
.auto, which evaluates to.mainwhen invoked on the main thread, otherwise.default.tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonCompletefrom being invoked.onCompleteThe callback that is invoked with the promise’s value.
Return Value
A new promise that will resolve to the same value as the receiver. You may safely ignore this value.
-
Registers a callback that will be invoked with the promise result, no matter what it is, and returns a new result.
Declaration
Swift
public func mapResult<T, E>(on context: PromiseContext, token: PromiseInvalidationToken? = nil, _ onComplete: @escaping (PromiseResult<Value, Error>) -> PromiseResult<T, E>) -> Promise<T, E>Parameters
contextThe context to invoke the callback on.
tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonCompletefrom being invoked and will cause the returnedPromiseto be cancelled.onCompleteThe callback that is invoked with the promise’s value. This callback returns a new result, which the returned promise will adopt the value of.
Return Value
A new
Promisethat adopts the result returned byonComplete. -
Registers a callback that will be invoked with the promise result, no matter what it is, and returns a new promise to wait on.
Declaration
Swift
public func flatMapResult<T, E>(on context: PromiseContext, token: PromiseInvalidationToken? = nil, _ onComplete: @escaping (PromiseResult<Value, Error>) -> Promise<T, E>) -> Promise<T, E>Parameters
contextThe context to invoke the callback on.
tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonCompletefrom being invoked and will cause the returnedPromiseto be cancelled.onCompleteThe callback that is invoked with the promise’s value. This callback returns a new promise, which the returned promise will adopt the value of.
Return Value
A new
Promisethat adopts the same value that the promise returned byonCompletedoes. -
Registers a callback that will be invoked with the promise result, no matter what it is, and returns a new result.
Declaration
Swift
public func tryMapResult<T, E>(on context: PromiseContext, token: PromiseInvalidationToken? = nil, _ onComplete: @escaping (PromiseResult<Value, Error>) throws -> PromiseResult<T, E>) -> Promise<T, Swift.Error> where E : ErrorParameters
contextThe context to invoke the callback on.
tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonCompletefrom being invoked and will cause the returnedPromiseto be cancelled.onCompleteThe callback that is invoked with the promise’s value. This callback returns a new result, which the returned promise will adopt the value of.
Return Value
A new
Promisethat adopts the result returned byonComplete, or is rejected ifonCompletethrows an error. -
Registers a callback that will be invoked with the promise result, no matter what it is, and returns a new promise to wait on.
Declaration
Swift
public func tryFlatMapResult<T, E>(on context: PromiseContext, token: PromiseInvalidationToken? = nil, _ onComplete: @escaping (PromiseResult<Value, Error>) throws -> Promise<T, E>) -> Promise<T, Swift.Error> where E : ErrorParameters
contextThe context to invoke the callback on.
tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonCompletefrom being invoked and will cause the returnedPromiseto be cancelled.onCompleteThe callback that is invoked with the promise’s value. This callback returns a new promise, which the returned promise will adopt the value of.
Return Value
A new
Promisethat adopts the same value that the promise returned byonCompletedoes, or is rejected ifonCompletethrows an error. -
Registers a callback that will be invoked with the promise result, no matter what it is, and returns a new result.
-
Registers a callback that will be invoked with the promise result, no matter what it is, and returns a new promise to wait on.
-
Registers a callback that will be invoked when the promise is resolved without affecting behavior.
This is similar to an
alwayscallback except it doesn’t create a newPromiseand instead returns its receiver. This means it won’t delay any chained callbacks and it won’t affect automatic cancellation propagation behavior.This is similar to
tap().always(on:token:_:)except it can be inserted into any promise chain without affecting the chain.Note
This method is intended for inserting into the middle of a promise chain without affecting existing behavior (in particular, cancellation propagation). If you are not inserting this into the middle of a promise chain, you probably want to use
then(on:token:_:),map(on:token:_:),catch(on:token:_:), oralways(on:token:_:)instead.See also
Declaration
Swift
@discardableResult public func tap(on context: PromiseContext = .auto, token: PromiseInvalidationToken? = nil, _ onComplete: @escaping (PromiseResult<Value, Error>) -> Void) -> Promise<Value, Error>Parameters
contextThe context to invoke the callback on. If not provided, defaults to
.auto, which evaluates to.mainwhen invoked on the main thread, otherwise.default.tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonCompletefrom being invoked.onCompleteThe callback that is invoked with the promise’s value.
Return Value
The receiver.
-
Returns a new
Promisethat adopts the result of the receiver without affecting its behavior.The returned
Promisewill always resolve with the same value that its receiver does, but it won’t affect the timing of any of the receiver’s other observers and it won’t affect automatic cancellation propagation behavior. Requesting cancellation of the returnedPromisedoes nothing.tap().always(on:token:_:)behaves the same astap(on:token:_:)except it returns a newPromisewhereastap(on:token:_:)returns the receiver and can be inserted into any promise chain without affecting the chain.Note
This method is intended for inserting into the middle of a promise chain without affecting existing behavior (in particular, cancellation propagation). If you are not inserting this into the middle of a promise chain, you probably want to use
then(on:token:_:),map(on:token:_:),catch(on:token:_:), oralways(on:token:_:)instead.See also
Declaration
Swift
public func tap() -> Promise<Value, Error>Return Value
A new
Promisethat adopts the same result as the receiver. Requesting this new promise to cancel does nothing. -
Registers a callback that will be invoked when the promise is cancelled.
Note
Like
tap,onCanceldoes not prevent automatic cancellation propagation if the parent has multiple children and all other children have requested cancellation. Unliketap, requesting cancellation ofonCancelwill cancel the parent if the parent has no other children.onCancel‘s behavior differs from the other standard obsrevers here as attaching anonCancelobserver to a promise that would otherwise be cancelled should not prevent the cancellation.Declaration
Swift
@discardableResult public func onCancel(on context: PromiseContext = .auto, token: PromiseInvalidationToken? = nil, _ onCancel: @escaping () -> Void) -> Promise<Value, Error>Parameters
contextThe context to invoke the callback on. If not provided, defaults to
.auto, which evaluates to.mainwhen invoked on the main thread, otherwise.default.tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonCancelfrom being invoked.onCancelThe callback that is invoked when the promise is cancelled.
Return Value
A new promise that will resolve to the same value as the receiver. You may safely ignore this value.
-
Returns a promise that adopts the same value as the receiver, and propagates cancellation from its children upwards even when it still exists.
Normally cancellation is only propagated from children upwards when the parent promise is no longer held on to directly. This allows more children to be attached to the parent later, and only after the parent has been dropped will cancellation requests from its children propagate up to its own parent.
This method returns a promise that ignores that logic and propagates cancellation upwards even while it still exists. As soon as all existing children have requested cancellation, the cancellation request will propagate to the receiver. A callback is provided to allow you to drop the returned promise at that point, so you don’t try to attach new children.
The intent of this method is to allow you to deduplicate requests for a long-lived resource (such as a network load) without preventing cancellation of the load in the event that no children care about it anymore.
Important
Do not give the returned promise directly to callers. Instead always hand back a child, such as returned from
makeChild. Otherwise automatic cancellation propagation won’t work as expected.Declaration
Swift
public func propagatingCancellation(on context: PromiseContext, cancelRequested: @escaping (_ promise: Promise<Value, Error>) -> Void) -> Promise<Value, Error>Parameters
contextThe context to invoke the callback on.
cancelRequestedThe callback that is invoked when the promise is requested to cancel, either because
.requestCancel()was invoked on it directly or because all children have requested cancellation. This callback is executed immediately prior to the cancellation request being propagated to the receiver.promiseThe same promise that’s returned from this method.
Return Value
A new promise that will resolve to the same value as the receiver.
-
Returns a promise that adopts the same value as the receiver.
This method is used in order to hand back child promises to callers so that they cannot directly request cancellation of a shared parent promise. This is most useful in conjunction with
propagatingCancellation(on:cancelRequested:)but could also be used any time a shared promise is given to multiple callers.Declaration
Swift
public func makeChild() -> Promise<Value, Error>Return Value
A new promise that will resolve to the same value as the receiver.
-
Passes the
Promiseto a block and then returns thePromisefor further chaining.This method exists to make it easy to add multiple children to the same
Promisein a promise chain.Note
Having multiple children on a singlePromisecan interfere with automatic cancellation propagation. You may want to usetap(on:token:_:)ortap()for your sibling children if you’re returning the result of the promise chain to a caller that may wish to cancel the chain.Example:
return urlSession.dataTaskAsPromise(for: url) .fork({ $0.tap().then(on: .main, { analytics.recordNetworkLoad($0.response, for: url) }) }) .tryMap(on: .utility, { try JSONDecoder().decode(Model.self, from: $0.data) })Declaration
Swift
public func fork(_ handler: (Promise) throws -> Void) rethrows -> Promise -
Requests that the
Promiseshould be cancelled.If the promise is already resolved, this does nothing. Otherwise, if the
Promiseregisters anyonRequestCancelhandlers, those handlers will be called.Note
Requesting that aPromiseshould be cancelled doesn’t guarantee it will be. If you need to ensure yourthenblock isn’t invoked, also use aPromiseInvalidationTokenand call.invalidate()on it.Declaration
Swift
public func requestCancel() -
Requests that the
Promiseshould be cancelled when the token is invalidated.This is equivalent to calling
token.requestCancelOnInvalidate(promise)and is intended to be used to terminate a promise chain. For example:urlSession.promiseDataTask(for: url).then(token: token, { (data) in … }).catch(token: token, { (error) in … }).requestCancelOnInvalidate(token)Declaration
Swift
@discardableResult public func requestCancelOnInvalidate(_ token: PromiseInvalidationToken) -> Promise<Value, Error>Parameters
tokenA
PromiseInvalidationToken. When the token is invalidated the receiver will be requested to cancel.Return Value
The receiver. This value can be ignored.
-
Returns a new
Promisethat adopts the value of the receiver but ignores cancel requests.This is primarily useful when returning a nested promise in a callback handler in order to unlink cancellation of the outer promise with the inner one. It can also be used to stop propagating cancel requests up the chain, e.g. if you want to implement something similar to
tap(on:token:_:).Note
This is similar to
tap()except it prevents the parent promise from being automatically cancelled due to cancel propagation from any observer.Note
The returned
Promisewill still be cancelled if its parent promise is cancelled.See also
Declaration
Swift
public func ignoringCancel() -> Promise<Value, Error> -
Returns a
Promisethat is already resolved with the given result.Note
This initializer has been renamed toinit(with:).See also
Promise.init(with:).Declaration
Swift
@available(*, deprecated, renamed: "init(with:﹚") init(result: PromiseResult<Value, Error>) -
Returns a
Promisethat resolves with the given result after a delay.Note
This initializer has been renamed toinit(on:with:after:).See also
Promise.init(on:with:after:).Declaration
Swift
@available(*, deprecated, renamed: "init(on:with:after:﹚") init(on context: PromiseContext = .auto, result: PromiseResult<Value, Error>, after delay: TimeInterval) -
Requests that the
Promiseshould be cancelled when the object deinits.This is equivalent to having the object hold a
PromiseInvalidationTokenin a property (configured to invalidate on deinit) and requesting the promise cancel on that token.Declaration
Swift
@discardableResult public func requestCancelOnDeinit(_ object: AnyObject) -> Promise<Value, Error>Parameters
objectAny object. When the object deinits the receiver will be requested to cancel.
Return Value
The receiver. This value can be ignored.
-
Two
Promises compare as equal if they represent the same promise.Two distinct
Promises that are resolved to the same value compare as unequal.Declaration
Swift
public static func == (lhs: Promise, rhs: Promise) -> Bool
-
Returns a value that can be used to cancel this promise without holding onto the full promise.
In particular, this acts like a weak reference, allowing for cancelling the promise without creating a retain cycle. Promise retain cycles normally break themselves anyway when the promise is resolved, but a misbehaving promise body may drop the resolver without ever resolving the promise. If the
Promisehas no more references to it this automatically cancels the promise, but a retain cycle prevents this.If you trust the promise provider to always resolve the promise, you can safely ignore this.
Declaration
Swift
public var cancellable: PromiseCancellable { get } -
Returns a new
TokenPromisethat wraps the receiver.A
TokenPromiseis an adapter that allows you to call methods on the wrappedPromisewhile automatically applying the givenPromiseInvalidationToken.Important
TokenPromiseautomatically cancels any returned childPromises when thePromiseInvalidationTokenis invalidated. If you do not want childPromises to be cancelled, pass the token to thePromisemethods manually instead of using.withToken(_:). SeeTokenPromisefor details.Declaration
Swift
public func withToken(_ token: PromiseInvalidationToken) -> TokenPromise<Value, Error>Parameters
tokenThe
PromiseInvalidationTokento use when calling methods on the receiver using the returnedTokenPromise.Return Value
A
TokenPromise. -
Returns a
Promisethat fulfills with the given value after a delay.Requesting that the promise be cancelled prior to it resolving will immediately cancel the promise.
This can be used as a sort of cancellable timer. It can also be used in conjunction with
when(first:cancelRemaining:)to implement a timeout that fulfills with a given value on timeout instead of rejecting with aPromiseTimeoutError.Declaration
Swift
public init(on context: PromiseContext = .auto, fulfilled value: Value, after delay: TimeInterval)Parameters
contextThe context to resolve the
Promiseon. This is generally only important when using callbacks registered with.immediate. If not provided, defaults to.auto, which evaluates to.mainwhen invoked on the main thread, otherwise.default. If provided as.immediate, behaves the same as.auto. If provided as.operationQueueit enqueues an operation on the operation queue immediately that becomes ready once the delay has elapsed.valueThe value the promise will be fulfilled with.
delayThe number of seconds to delay the promise by.
-
Returns a
Promisethat rejects with the given error after a delay.Requesting that the promise be cancelled prior to it resolving will immediately cancel the promise.
Declaration
Swift
public init(on context: PromiseContext = .auto, rejected error: Error, after delay: TimeInterval)Parameters
contextThe context to resolve the
Promiseon. This is generally only important when using callbacks registered with.immediate. If not provided, defaults to.auto, which evaluates to.mainwhen invoked on the main thread, otherwise.default. If provided as.immediate, behaves the same as.auto. If provided as.operationQueueit enqueues an operation on the operation queue immediately that becomes ready once the delay has elapsed.errorThe error the promise will be rejected with.
delayThe number of seconds to delay the promise by.
-
Returns a
Promisethat resolves with the given result after a delay.Requesting that the promise be cancelled prior to it resolving will immediately cancel the promise.
Declaration
Swift
public init(on context: PromiseContext = .auto, with result: PromiseResult<Value, Error>, after delay: TimeInterval)Parameters
contextThe context to resolve the
Promiseon. This is generally only important when using callbacks registered with.immediate. If not provided, defaults to.auto, which evaluates to.mainwhen invoked on the main thread, otherwise.default. If provided as.immediate, behaves the same as.auto. If provided as.operationQueueit enqueues an operation on the operation queue immediately that becomes ready once the delay has elapsed.resultThe result the promise will be resolved with.
delayThe number of seconds to delay the promise by.
-
Returns a new
Promisethat adopts the receiver’s result after a delay.Declaration
Swift
public func delay(on context: PromiseContext = .auto, _ delay: TimeInterval) -> Promise<Value, Error>Parameters
contextThe context to resolve the new
Promiseon. This is generally only important when using callbacks registered with.immediate. If not provided, defaults to.auto, which evaluates to.mainwhen invoked on the main thread, otherwise.default. If provided as.immediate, behaves the same as.auto. If provided as.operationQueueit enqueues an operation on the operation queue immediately that becomes ready once the delay has elapsed.delayThe number of seconds to delay the resulting promise by.
Return Value
A
Promisethat adopts the same result as the receiver after a delay. -
Returns a
Promisethat is rejected with an error if the receiver does not resolve within the given interval.The returned
Promisewill adopt the receiver’s value if it resolves within the given interval. Otherwise it will be rejected with the errorPromiseTimeoutError.timedOut. If the receiver is rejected, the returned promise will be rejected withPromiseTimeoutError.rejected(error).If the promise times out, the returned promise will be rejected using the same context. In this event,
.immediateis treated the same as.auto. If provided as.operationQueueit enqueues an operation on the operation queue immediately that becomes ready when the promise times out.Note
If the
delayis less than or equal to zero and thecontextis.immediateor.nowOr(_:)then the returned promise will already be resolved; if the receiver is already resolved the returned promise will adopt the same result, otherwise it will be rejected with.timedOut.Declaration
Swift
public func timeout(on context: PromiseContext = .nowOr(.auto), delay: TimeInterval) -> Promise<Value, PromiseTimeoutError<Error>>Parameters
contextThe context to invoke the callback on. If not provided, defaults to
.nowOr(.auto), which evaluates to.nowOr(.main)when invoked on the main thread, otherwise.nowOr(.default). The usage of.nowOrhere means that if the receiver has already been resolved when this method is called, the returned promise will likewise already be resolved. If the receiver has not already resolved then this behaves the same as passing.auto.delayThe delay before the returned promise times out. If less than or equal to zero, the returned
Promisewill be timed out at once unless the receiver is already resolved.Return Value
A new
Promise.
-
Returns a new promise with an error type of
Swift.Error.The new promise adopts the exact same result as the receiver, but if the promise resolves to an error, it’s upcast to
Swift.Error.Declaration
Swift
public var upcast: Promise<Value, Swift.Error> { get }
-
Returns a new promise with an error type of
Swift.Error.The new promise adopts the exact same result as the receiver. As the receiver’s error type is
NoError, the receiver cannot ever be rejected, but this upcast allows the promise to compose better with other promises.Declaration
Swift
public var upcast: Promise<Value, Swift.Error> { get }
-
Returns a new
Promisethat will be resolved using the given block.Declaration
Swift
public init(on context: PromiseContext, _ handler: @escaping (_ resolver: Resolver) throws -> Void)Parameters
contextThe context to execute the handler on.
handlerA block that is executed in order to fulfill the promise. If the block throws an error the promise will be rejected (unless it was already resolved first).
resolverThe
Resolverused to resolve the promise. -
Registers a callback that is invoked when the promise is fulfilled.
Declaration
Swift
public func tryThen(on context: PromiseContext = .auto, token: PromiseInvalidationToken? = nil, _ onSuccess: @escaping (Value) throws -> Void) -> Promise<Value, Error>Parameters
contextThe context to invoke the callback on. If not provided, defaults to
.auto, which evaluates to.mainwhen invoked on the main thread, otherwise.default.tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonSuccessfrom being invoked.onSuccessThe callback that is invoked with the fulfilled value.
Return Value
A new promise that will resolve to the same value as the receiver, or rejected if
onSuccessthrows an error. If the receiver is rejected or cancelled, the returned promise will also be rejected or cancelled. -
Registers a callback that is invoked when the promise is fulfilled.
Declaration
Swift
public func tryMap<U>(on context: PromiseContext, token: PromiseInvalidationToken? = nil, _ onSuccess: @escaping (Value) throws -> U) -> Promise<U, Error>Parameters
contextThe context to invoke the callback on.
tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonSuccessfrom being invoked. If the promise is fulfilled and the token is invalidated, the returned promise will be cancelled.onSuccessThe callback that is invoked with the fulfilled value.
Return Value
A new promise that will be fulfilled with the return value of
onSuccess, or rejected ifonSuccessthrows an error. If the receiver is rejected or cancelled, the returned promise will also be rejected or cancelled. -
Registers a callback that is invoked when the promise is fulfilled.
-
Registers a callback that is invoked when the promise is fulfilled.
Declaration
Swift
public func tryFlatMap<U, E>(on context: PromiseContext, token: PromiseInvalidationToken? = nil, _ onSuccess: @escaping (Value) throws -> Promise<U, E>) -> Promise<U, Error> where E : ErrorParameters
contextThe context to invoke the callback on.
tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonSuccessfrom being invoked. If the promise is fulfilled and the token is invalidated, the returned promise will be cancelled.onSuccessThe callback that is invoked with the fulfilled value.
Return Value
A new promise that will be eventually resolved using the promise returned from
onSuccess, or rejected ifonSuccessthrows an error. If the receiver is rejected or cancelled, the returned promise will also be rejected or cancelled. -
Registers a callback that is invoked when the promise is rejected.
Unlike
catch(on:_:)this callback can recover from the error and return a new value.Declaration
Swift
public func tryRecover(on context: PromiseContext, token: PromiseInvalidationToken? = nil, _ onError: @escaping (Error) throws -> Value) -> Promise<Value, Error>Parameters
contextThe context to invoke the callback on.
tokenAn optional
PromiseInvalidatonToken. If provided, callinginvalidate()on the token will preventonErrorfrom being invoked. If the promise is fulfilled and the token is invalidated, the returned promise will be cancelled.onErrorThe callback that is invoked with the rejected error.
Return Value
A new promise that will be fulfilled with the return value of
onError, or rejected ifonErrorthrows an error. If the receiver is rejected or cancelled, the returned promise will also be rejected or cancelled.
-
Returns a
Promisethat is already resolved with the given result.Declaration
Swift
public init(with result: Result<Value, Error>)
-
Returns a
Promisethat is rejected with an error if the receiver does not resolve within the given interval.The returned
Promisewill adopt the receiver’s value if it resolves within the given interval. Otherwise it will be rejected with the errorPromiseTimeoutError<Error>.timedOut. If the receiver is rejected, the returned promise will be rejected with the same error.If the promise times out, the returned promise will be rejected using the same context. In this event,
.immediateis treated the same as.auto. If provided as.operationQueueit enqueues an operation on the operation queue immediately that becomes ready when the promise times out.Note
If the
delayis less than or equal to zero and thecontextis.immediateor.nowOr(_:)then the returned promise will already be resolved; if the receiver is already resolved the returned promise will adopt the same result, otherwise it will be rejected with.timedOut.Declaration
Swift
public func timeout(on context: PromiseContext = .nowOr(.auto), delay: TimeInterval) -> Promise<Value, Swift.Error>Parameters
contextThe context to invoke the callback on. If not provided, defaults to
.nowOr(.auto), which evaluates to.nowOr(.main)when invoked on the main thread, otherwise.nowOr(.default). The usage of.nowOrhere means that if the receiver has already been resolved when this method is called, the returned promise will likewise already be resolved. If the receiver has not already resolved then this behaves the same as passing.auto.delayThe delay before the returned promise times out. If less than or equal to zero, the returned
Promisewill be timed out at once unless the receiver is already resolved.Return Value
A new
Promise.
View on GitHub
Promise Structure Reference