Make promise resolve in parralel
Tchoupinax opened this issue · 2 comments
Hello,
I would like to use all
method for revoving my promises in parrallel but it happens that promises are making one after one.
My example code is the following :
func performJobOne() -> Promise<String> {
sleep(10)
return Promise<String> { "Job One Finished" }
}
func performJobTwo() -> Promise<Bool> {
sleep(10)
return Promise<Bool> { true }
}
func performJobThree() -> Promise<Int> {
sleep(10)
return Promise<Int> { 10 }
}
all(performJobOne(),performJobTwo(),performJobThree())
.then { (results) in
print(results.0)
print(results.1)
print(results.2) }
.catch { $0.localizedDescription }
All
method resolves after 30 secondes. Is it possible to make it to resolve after ten seconds ?
Thank you,
Have a nice day :)
EDIT:
This code takes 6 seconds instead of 8. So it works. But i have to specify each time a new queue for all of my promises ? Why all
method could not do it by itself ?
func performJobOne() -> Promise<String> {
sleep(2)
return Promise<String> { "Job One Finished" }
}
func performJobTwo() -> Promise<Bool> {
sleep(2)
return Promise<Bool> { true }
}
func performJobThree() -> Promise<Int> {
sleep(2)
return Promise<Int> { 10 }
}
let concurrentQueue4 = DispatchQueue(label: "queuename", attributes: .concurrent)
let promise = Promise<String>(on: concurrentQueue4) { fulfilled, reject in
sleep(2)
return fulfilled("FINISH")
}
all(performJobOne(),performJobTwo(),performJobThree(), promise)
.then { (results) in
print(results.0)
print(results.1)
print(results.2)
print(results.3)
}
.catch { $0.localizedDescription }
Hi @Tchoupinax,
Take a look at the first item in this comment. In other words, all
is not intended to launch promises, it is an auxiliary synchronization construct to wait for them.
And as you've already figured out, in order to run promises simultaneously, you have to dispatch them on different queues, or on the one concurrent queue. Because there's the default queue used by all APIs, which is usually the main
serial one, and that can be configured, if needed.
Thanks.
Hello @shoumikhin,
Thank you to confirm that is the good way to do this. :)
RESOLVED: Previous code with DispatchQueue allows to make parrallel requests. :)