PromiseKit - 返回嵌套的承诺

时间:2016-07-10 21:46:49

标签: swift promisekit

我正在尝试使用PromiseKit,并且在绕过这个问题时遇到了一些麻烦。我有一个像

这样的功能
func lengthyOperation() -> Promise<TestObject> {
   return Promise { fulfil, reject in
     dispatch_async(GlobalUserInitiatedQueue) {
       do {
          let testObject = ...
          fulfil(testObject)
       } catch {
          reject(error)
       }
     } 
   }
}

我有另一个函数,我想称之为,并返回另一个承诺

func lengthyOperation2() -> Promise<Test2Object> {
   return Promise { fulfil, reject in 
        let test2Object = ...
        if test2Object == nil {
           lengthyOperation().then { testObject: TestObject in
               let test2Object = doSomethingWithTestObject(testObject) 
              fulfil(test2Object) //Compiler error here
           }.error {
              reject(error)
           }
        } else {
           fulfil(test2Object)
        }
   }
}

我收到编译错误

Cannot convert return expression of type 'Void' (aka '()') to return type 'AnyPromise'

几个问题:

  1. 我是否需要在promise呼叫中使用dispatch_async?
  2. 我如何调用并返回这样的嵌套承诺?
  3. 谢谢

    编辑:纠正一些伪代码

1 个答案:

答案 0 :(得分:0)

Just in case it helps somebody else,

  1. From the docs, the promise call is made on the same queue as which it is called from. So, if we want code to run in the background (in the first lengthyOperation()), it will need to be wrapped in a dispatch_async or similar.
  2. I seem to have gotten things working by the following pattern

    func lengthyOperation2() -> Promise<Test2Object> {
        return firstly {
           return lengthyOperation()
        }.then { (testObject: TestObject) -> Promise<Test2Object> in
           let test2Object = doSomethingWithTestObject(testObject)
           return Promise(test2Object)
        }
    }