PromiseKit导读——Day2

100 阅读1分钟

任务

总结

  • thendone操作的区别

then操作会返回一个promise,而done操作则不会返回,通常作为流程的终止点。

firstly {
    login()
}.then { creds in
    fetch(avatar: creds.user)
}.done { image in
    self.imageView = image
}
  • ensurefinally操作的区别

两者都能保证不管是成功还是失败,都会执行相关操作。ensure会返回一个Promise<Void>,可以继续接done操作,但finally是最后的终止流程。

func updateImage2() {
    firstly {
        login()
    }.then { creds in
        self.fetch(avatar: creds.user)
    }.done { image in
        self.imageView.image = image
    }.ensure {
        print("call ensure")
    }
    .done {
        print("call done")
    }
    .catch { error in
        print(error)
    }.finally {
        print("call finally")
    }
}

输出:

call ensure
call done
call finally
  • when操作:适用于要求多个操作统一完成后操作场景

对比起DispatchGroup的方式,when操作更简洁,且代码隔离更合理。

func operation1(completion: (String) -> Void) {
    
}

func operation2(completion: (String) -> Void) {
    
}

func operation1() -> Promise<String> {
    return Promise { resolver in
        resolver.fulfill("operation1")
    }
}

func operation2() -> Promise<String> {
    return Promise { resolver in
        resolver.fulfill("operation2")
    }
}

func makeOperation() {
    var result1: String!
    var result2: String!
    let group = DispatchGroup()
    group.enter()
    operation1 { result in
        result1 = result
        group.leave()
    }
    group.enter()
    operation2 { result in
        result2 = result
        group.leave()
    }
    
    group.notify(queue: .main) {
        let result = result1 + result2
        print(result)
    }
}

func makeOperation2() {
    firstly {
        when(fulfilled: self.operation1(), self.operation2())
    }.done { result1, result2 in
        let result = result1 + result2
        print(result)
    }
}
  • Guarantee操作:适用于永远不会失败的场景,即不会产生Error

func fetch2() -> Guarantee<String> {
    return Guarantee { seal in
        fetch2 { result in
            seal(result)
        }
    }
}

func doGuarantee2() {
    firstly {
        fetch2()
    }.done { result in
        print(result)
    } // no catch
}
  • mapcompactMap的区别

两者都是进行数据转换的作用,map操作返回的是一个可选值,即转换过程中可能返回一个nil对象,而compactMap操作返回的是一个确定的值,若转换过程中返回一个nil对象,它会转换为PMKError.compactMap,转接到catch处理了。

func doMap() {
    firstly {
        URLSession.shared.dataTask(.promise, with: URL(string: "")!)
    }.map {
        try JSONSerialization.jsonObject(with: $0.data) as? [String]
    }.done { arrayofString in
        if let arrayofString = arrayofString { // return optional value
            
        }
    }.catch { error in
        
    }
}

func doCompactMap() {
    firstly {
        URLSession.shared.dataTask(.promise, with: URL(string: "")!)
    }.compactMap {
        try JSONSerialization.jsonObject(with: $0.data) as? [String]
    }.done { arrayOfStrings in // not optional value
        
    }.catch { error in
        
    }
}