Swift & PromiseKit: Resolving ALL promises from a loop

泪湿孤枕 提交于 2020-01-13 09:44:10

问题


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
}


来源:https://stackoverflow.com/questions/43700548/swift-promisekit-resolving-all-promises-from-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!