PromiseKit 封装异步Api

来源:互联网 发布:小清新记账软件 编辑:程序博客网 时间:2024/05/16 10:50

Demo地址:https://github.com/jzhw0130/PromiseKitDemo  GitHub地址

功能很简单,模拟了一个用户登录的过程:登录,下载用户信息、更新用户信息。 

因为3个操作都是异步完成,且需要顺序调用,这样,就会写成这样(功能是没问题,看着是挺乱的吧。。。):

userLogin {

        if success {

            downloadUserInfo {

                if success {

                    uploadUserInfo {

                        if success {

                            //登录成功

                        }

                    }

                }

            }

        }

    }


最近学习了PromiseKit,将上述过程做了下封装,感觉不错,很简单,直接看源码即可:

self.loginWithUserName("John", password: "111111")

            .then(execute: { (token) ->Promise<[String:Any]>in

             

                return self.downloadUserInfo(token: token)

            }).then(execute: { (userInfo) -> (Promise<[String:Any]>)in

                

                return self.updateUserInfo(["Weight":60.0,"Height":180], token: userInfo["Token"]as!String)

            }).then(execute: { (uploadResult) ->Promise<[String:Any]>in

               

                return self.downloadUserInfo(token: uploadResult["Token"]as!String)

            }).then(execute: { (userInfo) ->Voidin

                print("userInfo:\(userInfo)")

            }).catch(execute: { (error)in

                print("error:\(error)")

            }).always(execute: {

                print("User login completed")

            })








原创粉丝点击