Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait on multiple PromiseKit promises which have a different payload?

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

like image 759
Serzhas Avatar asked Jun 10 '18 20:06

Serzhas


1 Answers

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)
  }
like image 182
Dan Karbayev Avatar answered Oct 02 '22 23:10

Dan Karbayev