如何使用PromiseKit重构swift回调以承诺

时间:2016-03-25 00:28:35

标签: swift promise promisekit

我尝试使用PromiseKit进行快速承诺后,尝试使用蓝鸟在节点中做一些经验。我使用回调进行身份验证的原始服务功能如下所示:

private func requestNewToken(email : String, password: String,
completion: (success: Bool, token: String?, userId : String?, message: String? ) -> Void) {

Alamofire.request(Router.Authenticate(email, password).URLRequest)
    .responseJSON { request, response, result in
        switch result {
        case .Success(let data):
            let jsonData = JSON(data)

            let success = jsonData["success"].bool!
            let message = jsonData["message"].string!

            if(success) {
                let token = jsonData["token"].string
                let userId = jsonData["_id"].string

                self.deleteSavedUser()
                self.saveUserToCoreData(email, password: password, token: token!, userId: userId!)
                completion(success: true, token: token, userId: userId, message:  message)
                return
            }

            completion(success: false, token: nil, userId: nil, message: message)
            print("Token request failed with error: \(message)")

        case .Failure(_, let error):
            print("Request failed with error: \(error)")
            completion(success: false, token: nil, userId : nil, message: nil)
        }
}
}

我试图改写成这样的东西:

private func requestNewTokenPromise(email : String, password:
String) -> Promise<UserLoginData?>{         
 return Promise{ fulfill, reject in             
   Alamofire.request(Router.Authenticate(email,password).URLRequest)
        .responseJSON { request, response, result in
            switch result {
            case .Success(let data):
                let jsonData = JSON(data)
                fulfill(jsonData)
            case .Failure(_, let error):
                print("Request failed with error: \(error)")
                reject(error)
            }
        }
}.then { json in

            let success = json["success"].bool!
            let message = json["message"].string!

            if(success) {
                let token = json["token"].string
                let userId = json["_id"].string

                self.deleteSavedUser()
                self.saveUserToCoreData(email, password: password, token: token!, userId: userId!) //sets the class's savedUser property

                return Promise(self.savedUser);
            }

            return Promise(nil);            
 }  
}

但是,我的第二行出现错误:

AuthenticationService.swift:147:6: Cannot convert return expression of type 'Promise<AnyObject?>' 
(aka 'Promise  Optional<AnyObject>> ') to return type 'Promise<UserLoginData?>' (aka 'Promise<Optional<UserLoginData>>')

我曾经想过通过Promise()来解决我已经履行了原始承诺类型的承诺。我哪里错了?

1 个答案:

答案 0 :(得分:0)

我认为代码可以直接发送到promises是不正确的,有时候你只需要包装一个回调:

public func login(email: String, password: String) -> Promise<UserLoginData> {
        return Promise { fulfill, reject in
            requestNewToken(email, password: password){
                success, returnToken, userId, message in

                if(!success){
                    reject(LoginError.LoginFailed(message))
                    return
                }
                self.deleteSavedUser()
                self.saveUserToCoreData(email, password: password, token: returnToken!, userId: userId!)
                let user = self.fetchUserFromCoreData()
                fulfill(user!)
            }
        }
    }