0x00 Chapter 4: Async
1.Resolving futures
Executes on a future
and returns another future
:
flatMap()
map()
if the callback that processes the EventLoopFuture
result returns an EventLoopFuture
, use flatMap()
if the callback returns a type other than
EventLoopFuture, use map()
2.Transform
Sometimes you don’t
care about the result
of a future, only that it completed successfully
you can simplify step 3 by using transform(to:)
3.Flatten
There are times when you must wait for
a number of futures to complete.
use flatten(on:)
flatten(on:)
waits for all
the futures to return as they’re executed asynchronously
by the same EventLoop
4.Multiple futures
If you have two
futures — get all the users from the database and get some information from an external API — you can use and(_:)
like this:
If the closure returns a non-future
result, you can use map(_:)
on the chained futures instead:
You can chain
together as many futures as required with and(_:)
but the flatMap
or map
closure returns the resolved futures in tuples
result is of type (([User], [Acronyms]), [Categories])
5.Creating futures
If an if statement
returns a nonfuture
and the else
block returns an EventLoopFuture
you must convert the non-future
into an EventLoopFuture
using request.eventLoop.future(_:)
6.Dealing with errors in the callback
The callbacks for map(_:)
and flatMap(_:)
are both non-throwing
if you call a method inside the closure that throws
use flatMapThrowing(_:)
flatMap(_:)
can’t throw, you must catch the error and return a failed future
7.Dealing with future errors
whenFailure()
flatMapErrorThrowing()
flatMapError()
8.Always
Sometimes you want to execute something no matter
the outcome of a future
result.always { //… }
9.Waiting
you may want to actually wait for
the result to return
use wait()
let savedUser = try user.save(on: database).wait()
This can only be used off
the main event loop
!
只能在主事件循环
之外
使用!
0x01 小五笔86版
App Store
搜索:小五笔
即可~