0

I am building a Swift app and using PromiseKit to make the async features more readable.

From the PromiseKit docs, I can see that it supports multiple concurrent promises. I wrote some code as follows to generate promises in a for loop then wait for them all to get fulfilled.

for index in 0...100 {
    let urlString = "https://someurl.com/item/\(index)"
    guard let url = URL(string: urlString) else { return }
    requestPromises += [URLSession.shared.dataTask(.promise, with: url).validate()]
}

firstly {
    when(fulfilled: requestPromises)
}.done {
    // process results
}

The example in the docs shows to write the promise as:

firstly {
    when(fulfilled: operation1(), operation2())
}.done { result1, result2 in
    //…
}

My problem is I don't want to write out result1, result2, ... result100. Is there a way to programmatically access the results?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
rhlsthrm
  • 769
  • 1
  • 12
  • 23
  • 1
    I had a quick run through the extend docs and both the [`Timeout` example](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#timeout) and [`when` Variants](https://github.com/mxcl/PromiseKit/blob/master/Documentation/GettingStarted.md#when-variants) documentation seem to show that you can use and array of promises, assuming they return the same generic return – MadProgrammer Jan 05 '19 at 01:27
  • @rhlsthrm show us function done declaration – Evgeniy Kleban Jan 05 '19 at 02:57
  • @MadProgrammer so I can declare the `done` argument as an array and loop through it? – rhlsthrm Jan 05 '19 at 02:59
  • 1
    In theory (not used PromiseKit for a while), yes, the results “should” be passed to done and should be in the same order – MadProgrammer Jan 05 '19 at 03:17
  • I tried to play around it and I couldn't find a way to achieve it... Means that I had to type `result1, result2 ... result100 in` – Ahmad F Jan 13 '19 at 11:02
  • @AhmadF it worked for me the way MadProgrammer specified. – rhlsthrm Jan 14 '19 at 04:38

1 Answers1

0

I was able to solve this the following way (thanks @MadProgrammer):

for index in 0...100 {
    let urlString = "https://someurl.com/item/\(index)"
    guard let url = URL(string: urlString) else { return }
    requestPromises += [URLSession.shared.dataTask(.promise, with: url).validate()]
}

firstly {
    when(fulfilled: requestPromises)
}.done { results in
    // process results
}
rhlsthrm
  • 769
  • 1
  • 12
  • 23
  • 1
    Ok, so what you should do is to pass only one parameter `results` which refers to the result of each promise, correct? – Ahmad F Jan 14 '19 at 08:34
  • I am getting: `Contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored` – Ahmad F Jan 14 '19 at 15:32