当前位置:网站首页>Continue to have a fever. Try the asynchronous operation of dart language. The efficiency is increased by 500%

Continue to have a fever. Try the asynchronous operation of dart language. The efficiency is increased by 500%

2022-06-24 07:41:00 Tangge engages in development

Preface

I posted an article yesterday 《Dart Development server , I have a fever ( SAO ) 了 》, Thank you for reading the homepage .

I have a fever today , And how to use it Dart Asynchronous operation of language . Speaking of asynchronous operation , play NodeJS My classmates smiled knowingly , This is our housekeeping skill . play PHP, JAVA My classmates will have a look , It means that we just look and don't talk .

Before the code demonstration , Let's start with a scenario . Suppose I have some beautiful sisters , I want to send an email to them , Show love . In this process , What the code needs to do :

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

In the process , What I care about is how long it takes to send an email , Because I have too many sisters , If an email takes too long , I can't take care of others . It's up there 4 In one step , Which steps will take time ?

Obviously ,1 and 4 Basically, it is absolutely time-consuming ,2 It's going to take some time , But the time is short ,3 It takes the longest , Because it involves network transmission , Too many uncontrollable factors .

What synchronization code looks like

Let's simulate the above process by synchronizing the code .

Suppose that saving information to the database requires 1 second , Sending an email to the other party's mailbox requires 5 second , Overall, it should be 6 Some more .

import 'dart:io';

main() {
  acceptRequest(); // Accept the request 
  saveToDb();      // Save to database , Not too time consuming ,  Suppose you need 1 second 
  sendLetter();    // Send mail to the other party's mailbox , It's very time consuming ,  Suppose you need 5 second 
  returnRes();     // Return results 
}

void acceptRequest() {
  print(DateTime.now().toString() + '  Accept the request ');
}

void saveToDb() {
  sleep(Duration(seconds: 1));
  print(DateTime.now().toString() + '  Database saved successfully ');
}

void sendLetter() {
  sleep(Duration(seconds: 5));
  print(DateTime.now().toString() + '  Email sent successfully ');
}

void returnRes() {
  print(DateTime.now().toString() + '  Return results ');
}

Execute it , Get the printed results

2021-06-29 16:40:44.993785  Accept the request 
2021-06-29 16:40:46.000240  Database saved successfully 
2021-06-29 16:40:51.002400  Email sent successfully 
2021-06-29 16:40:51.002400  Return results 

A simple calculation , From accepting the request to returning the result , The total time is 6 About seconds , In line with expectations .

What does asynchronous code look like

Said just now , I have many beautiful sisters , An email takes so long , How long will it take for so many sisters , Can you hurry up ?

Of course , The code is as follows :

main() async {
  acceptRequest(); // Accept the request 
  await saveToDb(); // Save to database , Not too time consuming ,  need 1 second 
  sendLetter(); // Send mail to the other party's mailbox , It's very time consuming ,  need 5 second 
  returnRes(); // Return results 
}

void acceptRequest() {
  print(DateTime.now().toString() + '  Accept the request ');
}

void saveToDb() async {
  await Future.delayed(Duration(seconds: 1));
  print(DateTime.now().toString() + '  Database saved successfully ');
}

void sendLetter() async {
  await Future.delayed(Duration(seconds: 5));
  print(DateTime.now().toString() + '  Email sent successfully ');
}

void returnRes() {
  print(DateTime.now().toString() + '  Return results ');
}

Execute it , Get the print results

2021-06-29 16:47:46.931323  Accept the request 
2021-06-29 16:47:47.956545  Database saved successfully 
2021-06-29 16:47:47.959539  Return results 
2021-06-29 16:47:52.960542  Email sent successfully 

This result , But I need to pay attention . There are two points to note :

  1. From receiving the request to returning the result , All in all 1 About seconds
  2. Email sent successfully , It appears after the returned result , interval 5 second

Why is that ? In fact, this is Dart The charm of language asynchronous operation .

Dart By default, tasks are executed in code order .

But when it comes to sendLetter It's time , Find out it's a async Asynchronous operations , And don't wait for it , Then just skip him , Implemented the following returnRes , So it prints out Return results

After returning the result , If it is a browser request , Then the browser request ends directly . But it's not over ,Dart Continued to execute the just skipped sendLetter, So I finally printed out Email sent successfully

As a whole , I sent an email this time , It only took 1 Second , And before it was 6 Second. , This efficiency improvement , A good 500%

Mm-hmm , That's great , I can take care of more sisters .

await async What the hell is it

The sharp eyed students may have seen , In the above code

main() async {
  acceptRequest(); // Accept the request 
  await saveToDb(); // Save to database , Not too time consuming ,  need 1 second 
  sendLetter(); // Send mail to the other party's mailbox , It's very time consuming ,  need 5 second 
  returnRes(); // Return results 
}

saveToDb Save database And sendLetter Sending oil prices is a time-consuming operation , Why? saveToDb I added await

This is because , saveToDb It's also asynchronous operation , If not await , It will look like sendLetter Just like sending email , Be skipped first , After the browser returns the result , To be carried out . This creates a problem , If writing to the database fails , But you've told the user that it was successful , Isn't that embarrassing ?

therefore , saveToDb I added await, tell Dart Although this code is asynchronous , You need to synchronize .

summary

When an operation is very time-consuming , We can set it to be asynchronous async, First return information to the user , Take your time .

If you want to make an asynchronous operation synchronous , You can add keywords await, Indicates that I am willing to wait for the asynchronous result .

Dart Provides a mechanism for asynchronous operation , We can use them easily .

play NodeJS I cried , Someone stole his housekeeping skills .

原网站

版权声明
本文为[Tangge engages in development]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/06/20210629183259026b.html