Thread Pitt
Thread Pitt

Reputation: 858

Swift & PromiseKit: Resolving ALL promises from a loop

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!

Upvotes: 7

Views: 6571

Answers (1)

CodeBender
CodeBender

Reputation: 36640

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
}

Upvotes: 11

Related Questions