7

I'm looking for a solution in Swift3 to resolve a dynamic number of promises all at once, e.g. like this sample in JavaScript:

var promises = [];
for(var i = 0; i < 5; i++) {
    var promise = $http.get('/data' + i);
    promises.push(promise);
}
$q.all(promises).then(doSomethingAfterAllRequests);

https://daveceddia.com/waiting-for-promises-in-a-loop/

There was a library call 'Craft' for Swift2 that could do that (https://github.com/supertommy/craft), but it's no longer maintained.

Does anyone know if or how I could do that with PromiseKit or another library?

Thx a bunch!

Nazmul Hasan
  • 10,130
  • 7
  • 50
  • 73
Thread Pitt
  • 716
  • 1
  • 6
  • 20

1 Answers1

11

You can look into when which may provide what you need and is covered here.

Use the loop to put your promises into an array and then do something like this:

when(fulfilled: promiseArray).then { results in
    // Do something
}.catch { error in
    // Handle error
}
CodeBender
  • 35,668
  • 12
  • 125
  • 132
  • 1
    Hi, thanks so much, perfect answer! I was so fixated on the .all that I didn't realize the array in the when(). I also found this one on the way, quite useful, but objective-c: http://philmitchell.github.io/PromiseKit/ – Thread Pitt Apr 30 '17 at 17:41
  • I have independent requests, which are not dependent on each other. The issue with fulfilled is if first has an error it will not go ahead for 2nd request and I will not get a response in done. Any suggestion for that? – HardikDG Sep 23 '18 at 05:11
  • 2
    @HardikDG You can use the `when(resolved: )` variant. This will wait on all of the provided promises, and then give you an array of all of their results. – clarkcox3 Oct 19 '18 at 19:47