如何使用 PromiseKit 6.3 返回 Promise<JSON>
Posted
技术标签:
【中文标题】如何使用 PromiseKit 6.3 返回 Promise<JSON>【英文标题】:How To Use PromiseKit 6.3 To Return Promise<JSON> 【发布时间】:2018-06-19 20:48:59 【问题描述】:我在从 PromiseKit 4.0 转换到 PromiseKit 6.3 时遇到问题。我正在尝试将此特定功能转换为新版本。我该怎么做?
func registerUser(_ email: String, givenName: String, familyName: String, password: String) -> Promise<JSON>
let req = urlRequestForPath("/user/create/local/", parameters: nil, method: .POST) as! NSMutableURLRequest
let queryString = stringFromParameters(["email": email.lowercased() as AnyObject, "given_name": givenName as AnyObject, "family_name": familyName as AnyObject, "password": password as AnyObject, "client_id": oauthClientId as AnyObject])
req.httpBody = queryString.data(using: String.Encoding.utf8, allowLossyConversion: false)
return URLSession.shared.dataTask(with: req as URLRequest).then(data: Data) -> JSON in
return try! JSON(data: data)
【问题讨论】:
【参考方案1】:它应该返回如下,
func registerUser(_ email: String, givenName: String, familyName: String, password: String) -> Promise<JSON>
let req = urlRequestForPath("/user/create/local/", parameters: nil, method: .POST) as! NSMutableURLRequest
let queryString = stringFromParameters(["email": email.lowercased() as AnyObject, "given_name": givenName as AnyObject, "family_name": familyName as AnyObject, "password": password as AnyObject, "client_id": oauthClientId as AnyObject])
req.httpBody = queryString.data(using: String.Encoding.utf8, allowLossyConversion: false)
let p = URLSession.shared.dataTask(.promise, with: req.pmkRequest)
return p.then (data, response) -> Promise<JSON> in
let json = try! JSON(data: data)
return Promise.value(json)
【讨论】:
以上是关于如何使用 PromiseKit 6.3 返回 Promise<JSON>的主要内容,如果未能解决你的问题,请参考以下文章
如何在 PromiseKit 中设置 when(fulfilled:)?
PromiseKit 如何将“when(resolved)”作为承诺返回?