PromiseKit - 带有重新加载第一个承诺的可选承诺
Posted
技术标签:
【中文标题】PromiseKit - 带有重新加载第一个承诺的可选承诺【英文标题】:PromiseKit - Optional promise with reload first promise 【发布时间】:2018-02-09 22:17:16 【问题描述】:我阅读了所有文档,但没有成功回答我的问题。 我有这种情况
我调用认证的api点-
如果响应是 200 到 299,我会填写
如果响应是 401,我调用 api 来刷新令牌
如果我刷新了 API 令牌,我需要重新调用第一个 api 点(以恢复所需的数据)。 你能帮我解决这个问题吗? 谢谢
【问题讨论】:
【参考方案1】:根据需要使用递归。使用 PromiseKit 你可以做一些很棒的事情。请参阅下面的刷新令牌请求流程。我希望下面的代码是自记录的。
// Define here your errors
enum MyErrors: Swift.Error
case unauthorized
case unknown
// Here is your primary function for retrieving remote data
func fetchRemoteData()
self.primaryRequest()
.then data in
return self.parsePrimaryRequest(response: data)
.done parsedResult in
// do something here if all chaining is success
.recover primaryRequestError in // this is your case for refresh token
if case MyErrors.unauthorized = primaryRequestError // if not authorized
self.refreshTokenRequest()
.then data in
return self.parseRefreshToken(data: data)
.done token in
// do someting with token, save it in secure store (keychain)
self.fetchRemoteData()
.catch refreshTokenError in
// refresh token request has failed
else
throw primaryRequestError
.catch primaryRequestError in
// here if error during request
func primaryRequest() -> Promise<Data>
return Promise seal in
// here you execure the request
// ...
// ...
let responseData = Data() // here you get data from URLSessionTask etc
let yourRequestStatusCode = 401 // take status code
let successCodes = Array(200...299) // define success codes
let authorizationErrorCode = 401 // define status code which requires performing refresh token request
if successCodes.contains(yourRequestStatusCode)
return seal.fulfill(responseData)
else if yourRequestStatusCode == authorizationErrorCode
throw MyErrors.unauthorized
else
throw MyErrors.unknown
func parsePrimaryRequest(response: Data) -> Promise<String>
return Promise seal in
// here you parse response
// ...
// ...
let parsedObject = "Awesome result"
seal.fulfill(parsedObject)
func refreshTokenRequest() -> Promise<Data>
return Promise seal in
// here you execure the request to refresh token
// ...
// ...
let responseData = Data() // here you get data from URLSessionTask etc
let yourRequestStatusCode = 401 // take status code
let successCodes = Array(200...299) // define success codes for refresh token request
if successCodes.contains(yourRequestStatusCode)
return seal.fulfill(responseData)
else
throw MyErrors.unknown
func parseRefreshToken(data: Data) -> Promise<String>
return Promise seal in
// here you parse response
// ...
// ...
let parsedObject = "00000000-00000000-00000000-00000000"
seal.fulfill(parsedObject)
【讨论】:
以上是关于PromiseKit - 带有重新加载第一个承诺的可选承诺的主要内容,如果未能解决你的问题,请参考以下文章