2
头图

Preface

Yesterday I posted an article "Dart development server, am I having a fever (sao)", thanks to the editor, I can see it on the homepage.

Continue to have a fever today, Dart ’s write about how to use the asynchronous operation of the 060e29fea3fbce language. Speaking of asynchronous operation, NodeJS how to smile, this is our housekeeping skill. The classmates who played PHP and JAVA also took a look, indicating that we just can't speak.

Before the code demonstration, we first assume a scenario. Suppose I have some beautiful sisters, and I want to send them an email to express my love. In this process, what the code needs to do:

  1. Receive request
  2. Save the content of my email to the database
  3. They also need to send the content of the email to their mailbox.
  4. Return result

In this process, what I care about is how long it takes to send an email, because there are too many sisters, and if an email takes too long, I can't take care of other people. Which of the above 4 steps will take time?

Obviously, 1 and 4 are basically not time-consuming, 2 takes a little time, but the time is very short, and 3 takes the longest because it involves network transmission and there are too many uncontrollable factors.

What is the synchronization code

We first simulate the above process by means of synchronous code.

Assuming that information is saved to the database needs 1 seconds, send mail to other mailboxes need 5 seconds, the general should be 6 points.

import 'dart:io';

main() {
  acceptRequest(); //接受请求
  saveToDb();      //保存到数据库,不太耗时, 假设需要1秒
  sendLetter();    //发送邮件到对方邮箱,非常耗时, 假设需要5秒
  returnRes();     //返回结果
}

void acceptRequest() {
  print(DateTime.now().toString() + ' 接受请求');
}

void saveToDb() {
  sleep(Duration(seconds: 1));
  print(DateTime.now().toString() + ' 保存数据库成功');
}

void sendLetter() {
  sleep(Duration(seconds: 5));
  print(DateTime.now().toString() + ' 发送邮件成功');
}

void returnRes() {
  print(DateTime.now().toString() + ' 返回结果');
}

Execute it and get the printed result

2021-06-29 16:40:44.993785 接受请求
2021-06-29 16:40:46.000240 保存数据库成功
2021-06-29 16:40:51.002400 发送邮件成功
2021-06-29 16:40:51.002400 返回结果

A simple calculation, from accepting the request to returning the result, it took a total of 6 seconds, which is in line with expectations.

What does asynchronous code look like?

As I just said, I have so many beautiful sisters, so an email takes so long, so how long does it take so many sisters, can you hurry up?

Of course, the code is as follows:

main() async {
  acceptRequest(); //接受请求
  await saveToDb(); //保存到数据库,不太耗时, 需要1秒
  sendLetter(); //发送邮件到对方邮箱,非常耗时, 需要5秒
  returnRes(); //返回结果
}

void acceptRequest() {
  print(DateTime.now().toString() + ' 接受请求');
}

void saveToDb() async {
  await Future.delayed(Duration(seconds: 1));
  print(DateTime.now().toString() + ' 保存数据库成功');
}

void sendLetter() async {
  await Future.delayed(Duration(seconds: 5));
  print(DateTime.now().toString() + ' 发送邮件成功');
}

void returnRes() {
  print(DateTime.now().toString() + ' 返回结果');
}

Execute it and get the printed result

2021-06-29 16:47:46.931323 接受请求
2021-06-29 16:47:47.956545 保存数据库成功
2021-06-29 16:47:47.959539 返回结果
2021-06-29 16:47:52.960542 发送邮件成功

You need to pay attention to this result. There are two points that need special attention:

  1. From receiving the request to returning the result, it took about 1 second in total
  2. The email was sent successfully, but it appeared after the returned result, with an interval of 5 seconds

why is it like this? In fact, this is the charm of the asynchronous operation of the Dart

Dart executes tasks in code order.

But when the execution reaches sendLetter , it is found that it is an async , and there is no need to wait for it for the time being, and then skip it directly, execute the following returnRes , so it prints out the return result

After the result is returned, if it is a browser request, then the browser request ends directly. But things did not end, Dart continued to implement just skip sendLetter , so in the end to print out the send mail success

Overall, it only took 1 seconds to send an email this time, compared to 6 seconds before. This efficiency increase is 500%

Hmm, it's great, I can take care of more sisters.

What is await async

The sharp-eyed students may see that in the code above

main() async {
  acceptRequest(); //接受请求
  await saveToDb(); //保存到数据库,不太耗时, 需要1秒
  sendLetter(); //发送邮件到对方邮箱,非常耗时, 需要5秒
  returnRes(); //返回结果
}

saveToDb saving database and sendLetter sending oil price are both time-consuming operations. Why is saveToDb added before await ?

This is because saveToDb is also an asynchronous operation. If you don't add await , it will be skipped first and executed after the browser returns the result just sendLetter This will cause a problem. If writing to the database fails, but you have told the user that it succeeded, isn't it embarrassing?

So, saveToDb is added in front of await to tell Dart that although this code is asynchronous, you have to execute it synchronously.

to sum up

When an operation is very time-consuming, we can set it to asynchronous async , first return information to the user, and then process it slowly.

If you want to make an asynchronous operation synchronous, you can add the keyword await to indicate that I am willing to wait for this asynchronous result.

Dart provides a mechanism for asynchronous operation, we can use them very conveniently.

The one who played NodeJS cried, but his housekeeping skills were stolen.


汤哥搞开发
34 声望4 粉丝