PromiseKit usage

See the code that your heart should be ten thousand grass mud horse ran!

Alamofire.request (URL method:.Get).ResponseJSON in switch response.result {response {case.Success (_): Alamofire.request (url1 method:.Get).ResponseJSON in switch response.result {response {case.Success (_): Alamofire.request (URL2 method:.Get).ResponseJSON in switch response.result {response {case.Success (_): doSomething (case).Failure (_): Print ("XXX error")}} case.Failure (_): Print ("XXX error")}} case.Failure (_): Print ("XXX error")}}

Your inner code must have been like this

Func request (with parameters: [String: Any] ->); Promise< NSDictionary> return {Promise {fulfill, reject in Alamofire.request ("https://httpbin.org/get", method:.Get, parameters: parameters).Validate (.ResponseJSON) (response) (in switch) {response.result {case.Success (let dict): fulfill (dict as NSDictionary case.Failure!) (let error): reject (error)}}}} func (threeRequest) -> Promise< > return firstly () {{request (with: ["test1": "first") {}.then (V) -> Promise< NSDictionary> in print ("", V) Return self.request (with: ["test2": "second") {}.then (V) -> Promise< NSDictionary> in print ("", V return self.request (with:) ["test3": "third") {}.then (V) in print ("", V}.catch in (error)) {print}} (error)

She is elegant, clean and easy to understand. Just as good as first love.
so how can you write such clean and easy to understand code?

Today we share a artifact – PromiseKit

Basic use

Promise {fulfill, reject in Alamofire.request ("https://httpbin.org/get", method:.Get, parameters: parameters).Validate (.ResponseJSON) (response) (in switch) {response.result {case.Success (let dict): fulfill (dict as NSDictionary case.Failure!) (let error): reject (error)}}}.then {dict in print (dict)}.catch (error in print) {(error)}

If you look at the functional Swift, this book should be familiar with Promise, but here are two callbacks, and the examples in the book have only one callback.

  • Fulfill (perform): pass the results to the then branch
  • Reject (denial): passing the results to the catch branch,
    , is it feeling humane, a commitment, fulfilling, or rejecting?.

Firstly

Document interpretation

Compare: NSURLSession.GET (url1).Then NSURLSession.GET (URL2) {}.then {NSURLSession.GET} With: {firstly (url3) NSURLSession.GET (url1)}.then NSURLSession.GET (URL2) {}.then {NSURLSession.GET} (url3)

In fact, the effect is to make the style more elegant

Always

From the literal sense, it’s always done. You can use it anywhere

Firstly session (}.then) {{data in Promise< [String: Any]> in (fulfill, reject) {do {let JSON = try JSONSerialization.jsonObject (with: data, options:.AllowFragments fulfill (JSON) as! [String: Any] catch {reject})}} {(error)}.always print (1111)}.then ({JSON) in print}.always (JSON) {print ("always", Thread.current) {}.catch (error) in print (error)}.always ("") {print}

When

When (fulfilled:, sessionPromise (), loginPromise ()),.Then {(data, dict), in, print (data, dict),}.catch {error, in, print (error)}

You can execute multiple Promise at the same time and eventually fall to a then

Race

Literal competition

Race (loginPromise (), loginPromise ()).Then {winner, in print (winner)}.catch {error in print (error)}

What’s the difference between him and when?:

  • Only the fastest one will fall into then
  • Promise generic must be the same

Then

Firstly {sessionPromise (}.then) (on:) DispatchQueue.global (data) {-> Promise< [String: Any]> in print ("global queue", Thread.current return Promise<); [String: Any]> in (fulfill, reject) {do {let JSON = try JSONSerialization.jsonObject (with: data, options:.AllowFragments fulfill (JSON) as [String! Any]: catch {reject})}} {(error)}.always print (1111, Thread.current) {}.then (JSON) in print (JSON, Thread.current) {}.always print (always, Thread.current) {}.catch (error) in Print (error}.always) {print} ("")

Explaining the callback that receives the fulfill branch, you can specify the queue to be executed by the current then branch

Wrap

The document says:
, However, you, use, some, other, that, doesn, framework, t, support, promises., inevitably, For, these, situations,, we, provide, PromiseKit.wrap

Just do not support promises, use this, no big understanding, useful friends reply, thank you

FAQ

  1. What is Promise?
    Promise is a way to link asynchronous tasks. Typically, asynchronous tasks perform a callback closure when asynchronous operations are completed (sometimes two closures are prepared, one represents success, and one represents failure)
  2. What’s the principle of Promise?
    Promise is essentially a state machine, and
    Promise is a Monad
  3. The source of Promise?
    Promise responded enthusiastically in the JavaScript community. Since Node.js’s design contains very many asynchronous operations, even a simple task requires a chained asynchronous callback. Even with only three or four such operations, the code becomes unwieldy. Promise ended the day when it was written, and Promise has written into the JavaScript ES6 specification. This blog introduces the operation mechanism of JavaScript Promise.

tail

If you use PromiseKit, you think your code is not elegant enough, then you recommend two libraries:
, Result,
, Moya

Recommended articles

RxSwift vs,
, Getting, Started, PromiseKit, with,
, Swift, Promise,
, Promise, PromiseKit several general mode,
state mode

This paper tests Demo