Swift & PromiseKit: Resolving ALL promises from a

2019-04-30 15:24发布

问题:

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!

回答1:

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
}