【Vapor】02 Chapter 4: Async

11 篇文章 1 订阅

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 搜索:小五笔 即可~
学习五笔的好帮手!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豪冷啊

你的鼓励是对我的认可!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值