Search code examples
swiftpromisekit

Swift access closure members programmatically


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?


Solution

  • 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
    }