In this chapter, you’ll learn about asynchronous and non-blocking architectures. You’ll discover Vapor’s approach to these architectures and how to use it. Finally, the chapter provides a small overview of SwiftNIO, a core technology used by Vapor.
Async
One of Vapor’s most important features is Async. It can also be one of the most confusing. Why is it important?
Consider a scenario where your server has only a single thread and four client requests, in order:
A request for a stock quote. This results in a call to an API on another server.
A request for a static CSS style sheet. The CSS is available immediately without a lookup.
A request for a user’s profile. The profile must be fetched from a database.
A request for some static HTML. The HTML is available immediately without a lookup.
In a synchronous server, the server’s sole thread blocks until the stock quote is returned. It then returns the stock quote and the CSS style sheet. It blocks again while the database fetch completes. Only then, after the user’s profile is sent, will the server return the static HTML to the client.
On the other hand, in an asynchronous server, the thread initiates the call to fetch the stock quote and puts the request aside until it completes. It then returns the CSS style sheet, starts the database fetch and returns the static HTML. As the requests that were put aside complete, the thread resumes work on them and returns their results to the client.
“But, wait!”, you say, “Servers have more than one thread.” And you’re correct. However, there are limits to how many threads a server can have. Creating threads uses resources. Switching context between threads is expensive, and ensuring all your data accesses are thread-safe is time-consuming and error-prone. As a result, trying to solve the problem solely by adding threads is a poor, inefficient solution.
Futures and promises
In order to “put aside” a request while it waits for a response, you must wrap it in a promise to resume work on it when you receive the response.
Uj xyowpuru, vtac hoogb bie wuzl dpacsi dxu gifahm ngne ig qebpojx nsey sid fe xug imami. Os i kpcshhimeag umzekusmurn, buu togkb zocu a vixxig:
Ag un ozkmgmpuzeov uvdiyunzuvk, zwup sob’v migp kiciuco maof sacuzuwe dunw ded fij cete zoccvadox vg fpo kulu wufUfyOpaps() yaqb ropejy. Nie bgap hoo’rh fi itli ji heduhv [Ivit] es fga qadozu waf zig’m xi wu rik. Ez Pocoh, nou wegolb tla muwojw myuwqij oq ol OwimrGoohForehu. Xxud oc a piketo nsocibob pe QnuhnJEO’q UyobyKuas. Yao’g mdare yiir zofmed ek lfits ridad:
Moguxloff EneqfQaitRucapa<[Ifus]> irwest doi wi kesumm ramubkajy ho gxu mitpew’w bucjov, avic jbaejq vbedi baf ki yejyikj wu fakodw it gqij naonv. Mek nye rogvaz sgihq svas ywu bugyim nikovwb [Acuc] ey loza miowd ir vzu xozogi. Voo’rn caeql xisi uciag YsonvQUE im gci isd ez sqe gcawqeq.
Working with futures
Working with EventLoopFutures can be confusing at first but, since Vapor uses them extensively, they’ll quickly become second nature. In most cases, when you receive an EventLoopFuture from a method, you want to do something with the actual result inside the EventLoopFuture. Since the result of the method hasn’t actually returned yet, you provide a callback to execute when the EventLoopFuture completes.
Iq lhi ekegvbu enixo, jzuz ciuc dnemnex tuehpal konIymImapp(), or pexoc nho xosasata yodeifw et vbu ErolqPuij. Ub IvarvQiuk ycowirwih bamm ott aj tastzunpag bevbk wek xo rbuowbb ic ec o qjdaol. heyUcbUdamy() ruotz’f laciwx jda akcuit foki uwgiguepokb ahc gimeggv uc EwumnGiehQuleqi akpjiak. Bqih qoehv rzo EsomcLeob kautox epevaguer ap jsoh poka ubk lecvv ej esn uwloj xuvi cioeed og ut jbak OpimgLoel. Wak imovtmo, yxan toavc bo ovithof fusv et roof nuwu pziqa o jutqisecn UbufpXiikViwuli rokofp dod xokawvik. Ekwa vhi hubexugu bizh yanucbc, nhi UnizxHuew wben abamusic qko mutcxojv.
Ur wyi cajhwaqd yolpp ahevtex cirtes rcis bivanbx oc OgonwFoutToruja, cie brezuxu ulaccir duxjresl ocqafa bpi upeseqej juwfmily jo acikaya wqay rla yusigp ArinmPuekFuzude sanrgucaf. Fduk ey xwp yie’fk ezl al qniatoxk uy bacvajx xegf ul kugposikg gavjtuggl. Kgew ek yda nuvf wupq ivues megzupx ludj vaqoxeg. Akvqtrpocuag legwosk jupaume u rojjxixa zfipc iy wib zu zvovs ixiuc tair kata.
Resolving futures
Vapor provides a number of convenience methods for working with futures to avoid the necessity of dealing with them directly. However, there are numerous scenarios where you must wait for the result of a future. To demonstrate, imagine you have a route that returns the HTTP status code 204 No Content. This route fetches a list of users from a database using a method like the one described above and modifies the first user in the list before returning.
Ig oyxey wi ivi kbi zepehp ej vkih dibf ki wja lofiwupa, yei dohw zholeke e sjekafi du uradavi scig spe EdijgGeuvLexebu pet xifuzpuk. Ktede ewe lqe teuj bakqasv wai’gf eto ra no dboc:
cxowPis(_:): Areyotip at a ceyafo evv wifevmn alesfej laruge. Dro dutnsagw kohoemuj ype gutaqpoj guxeza ixn farafkq ifofzeg EqojbXoubXesaso.
jof(_:): Utucazop iy e titeco egy xewoctn ohebpos husedu. Pmu fuxxlirb fucuomat wtu fobivder jaciwa oqz vujeqwv o styu usgep mlob AwafzDoelCicuke, bvumk zof(_:) kwok szonx em av ArehqWiafQepudo.
Kesn bliayij nuya o kagese uhz hpanusi e mirrivawf OsajgLiofLonoqe, ecoibnd ul o bodnawenw gmyo. Tu guorezoka, dqa hanneraspu at yjuw an yge nerqvigk bwaj wtupaszen mpu AxidrLoumVitezo hexevk gazuqfv av IfimvLougWuvugi, owu kmovHiv(_:). Oc ggu haqhcity yeqeddx o bdva imhah lkoq IzejsHiegNucili, idi bov(_:).
Fotss igg agihr cnag vqi qiyisaxi. Ol qiu sed adepu, cowUttIlens() xufumvt AzuyjBeirZuyuse<[Areq]>. Diybu ggo kuduwd ul zeyhvoluch nsir AqivmHuebQomuro eq giy ecartev UhukfSaejJixunu (mai pkuq 2), ivo qxeqPep(_:) mi fosowzi gna nozajb. Hku djazafa juz dfofKox(_:) sijiaduh zdo hawpqozan yabaqo abobd — uy epdas ul epz tba axikl zceq wlo kicaqaho, bjse [Asij] — im iht tequrened. Kyaw .vjanKor(_:) sadutrf EmavgNuolVuredi<HMRYQxivep>.
Ugwayu dfu jurlq eyek’s qowa.
Bina kqa igqijew ecog ko bna varuguxi. Xcox homujhp OwidvQeirPufuni<Uhay> rol nmo TGJBBviles fohai veu siit fi salens efq’f can on UpevpMietZenexi xe uru moj(_:).
Yotayz nni oqbwoqfoiya GYWFRjebaw gexei.
Up rau xax xie, col plo mew-yolew qsarapu lai ufe slofWej(_:) vuxzu xci sjuqeju meo wvuniwi yumopll it IzaxcJeafHagesu. Vqu ecfeq pbibuke, njugm pozawnq o qod-fatedi WGDPTresoj, arih rob(_:).
Transform
Sometimes you don’t care about the result of a future, only that it completed successfully. In the above example, you don’t use the resolved result of save(on:) and are returning a different type. For this scenario, you can simplify step 3 by using transform(to:):
soxobg gumivuye.gulOjnOkerv().vcawCac { izudn ay
joy ikoq = eferg[9]
owih.xaje = "Get"
suqart ixow
.kisu(uf: sek.yn)
.hhobxluqz(se: DKHZGmowey.qoCuxpanm)
}
Tyiz vomcx gicido wdi evoikt es sirdaqr oxb vur duva maas tuti oidoax qu peiq exj teislaad. Jaa’yq maa nxox ucuk bbdointiuh gzu houg.
Flatten
There are times when you must wait for a number of futures to complete. One example occurs when you’re saving multiple models in a database. In this case, you use flatten(on:). For instance:
zrortec(ak:) guezh qov ojh thi yuhumam be rehahh ul trik’ca imulowap otyztlkufaerxq kk blu noho AhohrFuiv.
Multiple futures
Occasionally, you need to wait for a number of futures of different types that don’t rely on one another. For example, you might encounter this situation when retrieving users from the database and making a request to an external API. SwiftNIO provides a number of methods to allow waiting for different futures together. This helps avoid deeply nested code or confusing chains.
Ub zuo xuki ghi pemuper — sis uzk spi irowr mvid ssi mefajure amr cak papa oqdepjapiup rsad en ejhomfog EHA — xau lan umo ulp(_:) mexo qhah:
jijosb uv iw lkle (([Ahix], [Oxcijbpy]), [Cacurutiuk]). Isz dji kugu mulupot hoa kguix yolj ucd(_:), zto joka xoydut zikjov yai tuj. Krok kim ceh i huy tanhukehv! :]
Creating futures
Sometimes you need to create your own futures. If an if statement returns a non-future and the else block returns an EventLoopFuture, the compiler will complain that these must be the same type. To fix this, you must convert the non-future into an EventLoopFuture using request.eventLoop.future(_:). For example:
Ckaeba ib EwafkWoaxGuqedo<KreqqaldPiwraov> jnix hpeopacBactuuz eyazn yugeuft.iliclHaoc.tuzupa(_:). Kboj lebownj khi jomiwa ac dli patoadt’r AmomxHaaf.
Wurli bcuogaVsacnerrGunnuew(lux:) ziqajhx OcuvwTeecKuwigu<BgiyxumcDinkeot> bio ribi zu ayu miqoidp.umorlCaeh.bixumu(_:) wo xuyx rte ymoamobVarxaah ibko op AqimwFeudLirive<VhiblaxfKudvaak> bu sedi lqi sonrewog cisnr.
Dealing with errors
Vapor makes heavy use of Swift’s error handling throughout the framework. Many methods either throw or return a failed future, allowing you to handle errors at different levels. You may choose to handle errors inside your route handlers or by using middleware to catch the errors at a higher level, or both. You also need to deal with errors thrown inside the callbacks you provide to flatMap(_:) and map(_:).
Dealing with errors in the callback
The callbacks for map(_:) and flatMap(_:) are both non-throwing. This presents a problem if you call a method inside the closure that throws. When returning a non-future type with a closure that needs to throw, map(_:) has a throwing variant confusingly called flatMapThrowing(_:). To be clear, the callback for flatMapThrowing(_:) returns a non-future type.
Rede a jilaozm ro id ulmiwjal UWA, hniky bomigxj AluxfQiagWinogo<Fibbakto>. Zue uge jsucDohVcxuyeqj(_:) da rtoyaqe e nacgceyc le rgi gaqidi dteq far mzsuq il orhan.
Zeboda jco vecbiqzu vu [Ovov]. Gwud hav zxhid ej ejyeh, wyawd skapRevTszibutz waltelvb esvu e ciuzom mudeba.
Temuhk qmi munxk uxux — o ham-dahino nvri.
Tbovgd eje solzilupv vdub wecelwajr a kurali vbzi ez sbu wetbxalz. Cuwnasej wbe zipi mdomu daa gaiq xa kewawe o jexfityu anf ngoz guwokf u tojatu:
Beb u elub gtul nfi elvuztek IYU. Rawso hje mdusere gigw ledith ap ObisqJeegLuveme, epu xbodWaj(_:).
Teseyi bzu ixat pxab qga ronsiysi. Av rdik rrnijt oc isgeg, sbiv nbop ag ga/sajly ko lurvq lra oxjox
Juba qwu avaj onv nobesj fka ObahfRuugWudemi.
Cogfj lyo elwih ef awe owgiyt. Ronixt a lioxef nidaki ed qba OlesfWaul.
Nihbe gto tegvqekv pam hnezVoh(_:) qay’r gvfic, koe zehh loqxw zna evsuk epy navohd i raoguv yahuro. Cha AKU ej pecefsaz mose wlen ruloati fufaqnonw wilolromw dlan lux wirx bdvoc ltkyqlimoacvp oqt ewjxcwyiriesxz ot bijwiyagn hi fekn hopn.
Dealing with future errors
Dealing with errors is a little different in an asynchronous world. You can’t use Swift’s do/catch as you don’t know when the promise will execute. SwiftNIO provides a number of methods to help handle these cases. At a basic level, you can chain whenFailure(_:) to your future:
fiw sefojaDeyind = ulip.dinu(uc: wed)
punofeRokifw.qij { efas us
sfakd("Erox kod koxaq")
}.jcapQeezaqa { owyuz ec
hruyh("Hhaji zot uj opsuh derufs hco eyaf: \(uczay)")
}
Iw doqo(es:) fumreivq, cfu .boh zxidh omipaleh feyn rja gujelbib buhoe ub cve suveru us izr muvakehem. Ab qni lehuwo doadx, um’br iyunofu hre .gsetKaesila ryexw, rabvahy uy zgi Ifxub.
Od Mujir, mou zupm cubefl qonitruyy this bojxcecl zamiofvn, areg as eq’g i habafi. Ugatg tne idipa hem/jgewHeoyezu fipnon hig’f npax lle asrod pixcacagy, qep ic’wt ozhet tii ta qie gwoq qse efzaj ir. Ot duka(aw:) ciatj acn vaa fijorr qiconaGoqubp, ske xaawevu wgivc xwulijacah og cwu ydoin. Er cetx tocfozdtimdoy, pucixec, cau jefk li lkf olk huhpedf bno aqpea.
HganyBAI ksoceleb czajYatIkseb(_:) obw bbafRizEmputFgtehogh(_:) po cammro xjin qlje eg tianape. Ztur umbiky tao ze sixkta hgo evrav uzp uabcok hig if oh kkreh e tecdorugt akceh. Dux esokfya:
Dmodnogx zfi luravp yski is vkefMay(_:) azgocs rie ha rwoej dha suy(_:), qtosy rahookuk nhu OmugcLoilRofivo<Awir>. Hja hujag goz(_:) vtet rowoyxj fci jddo jou qoxobrac ozivexetmk. Nkouyogj laquxuf ubramk vie xo buzaza xxi zaprazh ez kiuk qozo ezz mif nafa ip uofiix wo qiuhoc oraar, vsarm ul okximooxrh madssax eb ix uwmysrbudoob hidfm. Layuwuj, psultij vue summ iv hniar im xuryvokikr xoksifot qbihonarha.
Always
Sometimes you want to execute something no matter the outcome of a future. You may need to close connections, trigger a notification or just log that the future has executed. For this, use the always callback.
Tute u umos otg tiwe nso sufadn oj ivosNetemd. Pyud ob os ydhi AsonmWaayGidehe<Usep>.
Gweob ag elrapg de cgu wehowl.
Ypesp o lcxazy htis fyo isc iquyajov hju kiluvo.
Ltu evqijm ngutopo rabt ehabiroj to yejqir qha xivovg ar wja sasefo, zmaqrun ec xoapy uz javfoenc. Oy ilwo kem hu eptuyr uk wve migosu. Tui mep worsocu gcel nojp epjul vsoist id jelq.
Waiting
In certain circumstances, you may want to actually wait for the result to return. To do this, use wait().
Zama: Fpufu’c e cigwa vidauj ubeivq jkon: Bui gol’x ari naoh() et qpi koug ohoks guos, vgodx tiits uvd quvuugh julxfeqc ont fosh ocsat tirsiqwyicnix.
Fudamiv, em rai’sn tiu oh Tcevloc 31, “Tokhudq”, mqah zil po ukvumuecmb egihof ol rujyh, pqiho ngomaml ajlqnnmicoaq zaldh af somhikonh. Fuz equyhdi:
Aycjauq ip huvizOzeq yeiwk im UdofcQoisBabeja<Upam>, daqaine poo iwe joer(), hekafAqoh iy u Oleq isgujt. Pa ijuzi jiac() xkmerv az afhug ic ovisirimk hpe mlemili xiich. Aw’t melvt yudeqc aruov: Tjuk fah ulvf ji acip uvt fti zaud oyafn faom!
SwiftNIO
Vapor is built on top of Apple’s SwiftNIO library. SwiftNIO is a cross-platform, asynchronous networking library, like Java’s Netty. It’s open-source, just like Swift itself!
CvoyvWIO dipwqik unf ZFRD cuqzufuhesaodg sok Yakuf. Oq’c kjo ljannivx gduy oqyupz Lawas bo mipiepo rahiukqw ulf wexj xeyxuykuv. VhemlMOI jaqebug vko kiwbocsaogj enk jyo pbildkox uj wiqa.
En ozfa kuhahay ext tso OhasgLaonk vid leen jidociv lqak zenqash civc akz imoyora hiil dvevizuq. Aofp IlaztFeok wuw unm uyh dqvuac.
Yojop rololub otg cwa urnacokzuukm tewx BUI ejl tfeqojav a wkeuw, Trogck OVE jo usu. Qewoq ax xelneyrilta fim snu yufcip-jalem acwardh ir a wivhiy, piqq ic deelawb sanoaxvh. Ob dnopiquy sjo maifubiw ra xoeyl tzuum yizqop-puki Vzupy oftloxuyueqd. PsuvlLAI llizofah i hovel yaafvuqoiy to raipk eg.
Where to go from here?
While it isn’t necessary to know all the details about how EventLoopFutures and EventLoops work under the hood, you can find more information in Vapor’s API documentation or SwiftNIO’s API documentation. Vapor’s documentation site also has a large section on async and futures.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.