Search code examples
swiftpromisekit

How to return a modified result in a promise as a promise


I'm using promiseKit 6 with the extensions for Alamofire. In the function bellow I'm looking to return Promise<JSON> (I use swiftyJson) but the response from the alamofire call is a Promise containing a tuple: Promise<(json: Any, response: PMKAlamofireDataResponse)>

when I get that from the first then, how can I continue to return just the json part? thanks :)

return firstly {
  self.requestClient.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON()
}.then { arg in
  let (json, rsp) = arg
  return json
}

I also get this error: Cannot convert return expression of type 'Promise<_.T>' to return type 'Promise<JSON>' on the line: }.then { arg in ...


Solution

  • You should cast Any to JSON, try this (not tested), but documentation said you could use map/compactMap https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md

    return firstly {
        self.requestClient.request(url, method: .get, parameters: nil, 
              encoding: JSONEncoding.default, headers: nil).responseJSON()
    }.compactMap { data, rsp in
       return data as? JSON
    }