当前位置:网站首页>Dart series part: asynchronous programming in dart
Dart series part: asynchronous programming in dart
2022-06-24 01:05:00 【Procedural stuff】
brief introduction
be familiar with javascript Our friends should know , stay ES6 Introduced in await and async The grammar of , It is convenient for asynchronous programming , To get rid of hell .dart As a new language , There is no reason not to inherit this excellent quality . Very natural ,dart There are also await and async Language , Let's see .
Why asynchronous programming
So why use asynchronous programming ? Can't it be solved only by synchronization ?
In fact, in most cases, synchronization is enough , But in the following cases , The synchronized scenario is still flawed .
- It takes a long time to download data from the network .
- How long it takes to read the database .
- Reading data from a file .
In conclusion , If some operations take a lot of time , Then you can use asynchronous programming .
How do you use it?
async Is the descriptor of the method , If you want to use await, We must cooperate with async Use it together :
Future<void> checkVersion() async {
var version = await lookUpVersion();
// Do something with version
}Be careful ,await Usually followed by Future object .
Let's look at an example of using asynchronous programming incorrectly :
String createOrderMessage() {
var order = fetchUserOrder();
return 'Your order is: $order';
}
Future<String> fetchUserOrder() =>
Future.delayed(
const Duration(seconds: 2),
() => 'Order one!',
);
void main() {
print(createOrderMessage());
}The above code is intended to print out the data taken from the database , But the result is not as expected , And the reason is fetchUserOrder Method is an asynchronous method , So it won't return immediately , This causes the result to fail to print .
Use the above code async rewrite :
Future<String> createOrderMessage() async {
var order = await fetchUserOrder();
return 'Your order is: $order';
}
Future<String> fetchUserOrder() =>
Future.delayed(
const Duration(seconds: 2),
() => 'Large Latte',
);
Future<void> main() async {
print('Fetching user order...');
print(await createOrderMessage());
}Future
We are using async and await Used in the process of Future. stay java in Future Represents the execution result of the thread . stay dart in Future Represents the result of an asynchronous execution .
Future There are two states :uncompleted perhaps completed.
When you first execute an asynchronous function , An incomplete is returned Future. This unfinished Future It will wait for the completion or failure of asynchronous execution .
Whether the asynchronous program succeeds or fails , Finally, a completion status will be returned .
async Back to Future Can be generic , Represents the specific type returned when , such as Future Indicates that a string is returned , and Future Indicates that no value is returned .
Here are two examples of different returns :
Future<String> fetchUserOrder() {
return Future.delayed(const Duration(seconds: 2), () => 'Large Latte');
}
Future<void> fetchUserOrder() {
return Future.delayed(const Duration(seconds: 2), () => print('Large Latte'));
}The following is an example of an exception :
Future<void> fetchUserOrder() {
return Future.delayed(const Duration(seconds: 2),
() => throw Exception('Logout failed: user ID is invalid'));
}Asynchronous exception handling
stay async The function of , Yes await Exception thrown in asynchronous method of , It can be used directly try catch To catch exceptions :
try {
print('Awaiting user order...');
var order = await fetchUserOrder();
} catch (err) {
print('Caught error: $err');
}Calling asynchronous functions in synchronous functions
It's described above fetchUserOrder() Back to a Future, Represents an asynchronous process .
So if it's a synchronous method , such as main() Function , How to call asynchronous methods , And get the return value ?
await Surely not , because await Only in async Call in the method . You can use then sentence :
fetchUserOrder().then(order=>'do something');
then The statement waits for the asynchronous execution to return the result , And then process the results , It's actually equivalent to javascript Callback in .
summary
That's all dart in async and await Usage of .
This article has been included in http://www.flydean.com/12-dart-async/ The most popular interpretation , The deepest dry goods , The most concise tutorial , There are so many tricks you don't know about waiting for you to discover !
边栏推荐
- Arm learning (7) symbol table and debugging
- Is it safe to open an account for shares of tongdaxin?
- Shengdun technology joined dragon lizard community to build a new open source ecosystem
- 【小程序】相对路径和绝对路径的表示符
- Shardingsphere-proxy-5.0.0 implementation of capacity range partition (V)
- Messy knowledge points
- 分别用SVM、贝叶斯分类、二叉树、CNN实现手写数字识别
- 通达信股票开户是安全的吗?
- Pad User Guide
- WinSCP和PuTTY的安装和使用
猜你喜欢

Shardingsphere-proxy-5.0.0 implementation of capacity range partition (V)

Alibaba interview question: multi thread related

C language: structure array implementation to find the lowest student record

Error reported using worker: uncaught domexception: failed to construct 'worker': script at***

使用递归形成多级目录树结构,附带可能是全网最详细注释。

Zhongshanshan: engineers after being blasted will take off | ONEFLOW u
![[CVPR 2022] high resolution small object detection: cascaded sparse query for accelerating high resolution smal object detection](/img/79/7dfc30565ddee0769ef5f1bc239b5d.png)
[CVPR 2022] high resolution small object detection: cascaded sparse query for accelerating high resolution smal object detection

苹果Iphone14搭载北斗导航系统,北斗VS GPS有哪些优势?

一次 MySQL 误操作导致的事故,「高可用」都顶不住了!

13 `bs_ duixiang. Tag tag ` get a tag object
随机推荐
Cross domain and jsonp
跨域和JSONP
【ICPR 2021】遥感图中的密集小目标检测:Tiny Object Detection in Aerial Images
985 Android programmers won the oral offer of Alibaba P6 in 40 days. After the successful interview, they sorted out these interview ideas
After the deployment of Beidou navigation system, why didn't we launch a high-precision map similar to Google maps?
[ICPR 2021] tiny object detection in aerial images
An accident caused by a MySQL misoperation, and the "high availability" cannot withstand it!
[CVPR 2020 oral] a physics based noise formation model for extreme low light raw denoising
What problems need to be solved by MES management system in the era of intelligent manufacturing
想开户炒股,通过网上进行股票开户安全吗?-
DML operation
C语言:递归实现N的阶乘
Theoretical analysis of countermeasure training: adaptive step size fast countermeasure training
VS2022保存格式化插件
Real time preview of RTSP video based on webrtc
[CVPR 2022] high resolution small object detection: cascaded sparse query for accelerating high resolution smal object detection
Dart series: using generators in dart
[technical grass planting] use webhook to automatically deploy my blogs on multiple sites in Tencent cloud
Definition of logic
Isn't this another go bug?