【Vapor】02 Chapter 4: Async

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 搜索:小五笔 即可~
请添加图片描述


猜你喜欢

转载自blog.csdn.net/xjh093/article/details/123593626