In my project, I have numerous functions which asynchronously fetch data from the underlying data source and return result as a Promise<T>
, where T
is an optional model object.
I need to fetch 2 different, independent objects in parallel. For that I've tried to use when(resolved: [Promise<T>])
function:
let userPromise: Promise<User> = fetchUser(with: userID)
let documentPromise: Promise<Document> = fetchDocument(with: documentID)
when(resolved: [userPromise, documentPromise]).done {
...
}
But I'm getting an error Cannot invoke 'when' with an argument list of type '(resolved: [Any])'
. I've tried to assign promises to explicitly declared array:
let promises: [Promise<Any>] = [userPromise, documentPromise]
but now I'm getting an error that Promise<User>
cannot be assigned to Promise<Any>
. Frankly, I can't wrap my mind around it. What's the problem there?
P.S. To make things easier to grasp, I have created the following snippet:
func getPromise() -> Promise<String> {
return Promise<String>.pending().promise
}
let promise: Promise<Any> = getPromise()
which produces the similar error: Cannot convert value of type 'Promise<String>' to specified type 'Promise<Any>'
Any ideas how to solve it? Thanks!
Environment: PromiseKit 6.2.4, Swift 4.1, Xcode 9.4
when(resolved:)
is declared so that it only accepts promises with the same type. Here's its signature:
public func when<T>(resolved promises: Promise<T>...)
Do you particularly need a non-rejecting when(resolved:)
? Have you tried when(fulfilled:_:)
? The difference is that the latter rejects as soon as one of the provided promises rejects.
If using when(fullfilled:_:)
is possible then you could write something like this:
when(fulfilled: [userPromise, documentPromise])
.done { user, document in
// ...
}
.catch { error in
// either of promises has been rejected
print(error)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With