google / promises

Promises is a modern framework that provides a synchronization construct for Swift and Objective-C.
Apache License 2.0
3.8k stars 294 forks source link

Make promise resolve in parralel #114

Closed Tchoupinax closed 5 years ago

Tchoupinax commented 5 years ago

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 }

Allmethod 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 }
shoumikhin commented 5 years ago

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.

Tchoupinax commented 5 years ago

Hello @shoumikhin,

Thank you to confirm that is the good way to do this. :)

RESOLVED: Previous code with DispatchQueue allows to make parrallel requests. :)