20 minutes with async and async

Grape City technical team 2020-12-11 08:55:00
minutes async async


Reprint please indicate the source : Grape city official website , Grape city provides professional development tools for developers 、 Solutions and services , Enabling developers .
The source of the original text is :https://www.freecodecamp.org/news/learn-promise-async-await-in-20-minutes/

 

Generally in development , Check the Internet API The operation is often time-consuming , This means that it may take some time to get a response . therefore , In order to avoid the situation that the program does not respond to the request , Asynchronous programming has become a basic skill for developers .

stay JavaScript When processing asynchronous operations in , Usually, we often hear "Promise " The concept . But to understand how it works and how to use it may be more abstract and difficult to understand .

that , In this article, we will help you understand their concept and usage more quickly through practice , So it's different from many traditional, dry tutorials , We'll start with the following four examples :

  • Example 1: Explain with birthday Promise Basic knowledge of
  • Example 2: A game of guessing numbers
  • Example 3: from Web API Get country information from
  • Example 4: from Web API To get a list of countries around a country

Example 1: Explain with birthday Promise Basic knowledge of

First , Let's take a look first Promise What is the basic form of .

Promise There are three states in execution :pending( In execution )、fulfilled( success )、rejected( Failure ).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
new   Promise( function (resolve, reject) {
     if   ( /* Asynchronous operation succeeded */ ) {
         resolve(value);  // take Promise The status of the padding Change it to fulfilled
     }  else   {
         reject(error);  // take Promise The status of the padding Change it to rejected
     }
})
There are three prototypes to implement then、 catch 、finally
promise
.then((result) => {
     //promise Being accepted or refused to proceed
})
. catch ((error) => {
     //promise The situation of being rejected
})
.finally (() => {
     //promise When finished , It will be carried out in any case
})

The introduction of the basic form is completed , So let's start with the following example .

A user story : My friend Kayo Promise on my birthday in two weeks Party Make a cake for me .

If everything goes well and Kayo If you're not sick , We'll get a certain amount of cake , But if Kayo ill , We don't have any cake . But with or without cake , We still have a birthday Party.

So for this example , We translate the above background story into JS Code , First, let's create a return Promise Function of .

1
2
3
4
5
6
7
8
9
10
11
const onMyBirthday = (isKayoSick) => {
   return   new   Promise((resolve, reject) => {
     setTimeout(() => {
       if   (!isKayoSick) {
         resolve(2);
       }  else   {
         reject( new   Error( "I am sad" ));
       }
     }, 2000);
   });
};

stay JavaScript in , We can use new Promise() Create a new Promise, It takes a parameter as :(resolve,reject)=>{} Function of .

In this function ,resolve and reject Is a callback function provided by default . Let's take a closer look at the code above .

When we run onMyBirthday function 2000ms after .

  • If Kayo No illness , So let's use 2 Execute for parameters resolve function
  • If Kayo ill , So we use new Error("I am sad") Execute as parameter reject. Although you can pass anything you want to reject as an argument , But it is recommended that it be passed on to Error object .

Now? , because onMyBirthday() Back to a Promise, We can visit then、catch and finally Method . We can also visit earlier in then and catch To pass on to resolve and reject Parameters of .

Let's understand the concept through the following code

If Kayo No illness

1
2
3
4
5
6
7
8
9
10
onMyBirthday( false )
   .then((result) => {
     console.log(`I have ${result} cakes`);  // Console printing “I have 2 cakes” 
   })
   . catch ((error) => {
     console.log(error);  // Don't execute
   })
   .finally(() => {
     console.log( "Party" );  // Console printing “Party”
   });

If Kayo Fall ill

1
2
3
4
5
6
7
8
9
10
onMyBirthday( true )
   .then((result) => {
     console.log(`I have ${result} cakes`);  // Don't execute
   })
   . catch ((error) => {
     console.log(error);  // Console printing “ I'm sorry ”
   })
   .finally(() => {
     console.log( "Party" );  // Console printing “Party”
   });

 

I believe that through this example you can understand Promise Basic concepts of .

Let's start with an example 2

Example 2: A game of guessing numbers

Basic needs :

  • The user can enter any number
  • System from 1 To 6 A number is randomly generated in
  • If the user inputs a number equal to the system random number , To the user 2 branch
  • If the user input number is different from the system random number 1, To the user 1 branch , otherwise , To the user 0 branch
  • Users can play as long as they want

For the above requirements , So let's create one first enterNumber Function and returns a Promise:

1
2
3
4
5
const enterNumber = () => {
   return   new   Promise((resolve, reject) => {
     // Start coding from here
   });
};

The first thing we need to do is ask the user for a number , And in 1 To 6 Choose a number randomly between :

1
2
3
4
5
6
const enterNumber = () => {
   return   new   Promise((resolve, reject) => {
     const userNumber = Number(window.prompt( "Enter a number (1 - 6):" ));  // Ask the user for a number
     const randomNumber = Math.floor(Math.random() * 6 + 1);  // Choose one from 1 To 6 The random number
   });
};

When the user enters a value that is not a number . In this case , We call reject function , And throw an error :

1
2
3
4
5
6
7
8
9
10
const enterNumber = () => {
   return   new   Promise((resolve, reject) => {
     const userNumber = Number(window.prompt( "Enter a number (1 - 6):" ));  // Ask the user for a number
     const randomNumber = Math.floor(Math.random() * 6 + 1);  // Choose one from 1 To 6 The random number
 
     if   (isNaN(userNumber)) {
       reject( new   Error( "Wrong Input Type" ));  // When the value entered by the user is not a number , Throw an exception and call reject function
     }
   });
};

below , We need to check userNumber Is it equal to RanomNumber, If equal , We give users 2 branch , Then we can execute resolve Function to pass a object { points: 2, randomNumber } object .

If userNumber And randomNumber Difference between 1, So we give users 1 branch . otherwise , We give users 0 branch .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
return   new   Promise((resolve, reject) => {
   const userNumber = Number(window.prompt( "Enter a number (1 - 6):" ));  // Ask the user for a number
   const randomNumber = Math.floor(Math.random() * 6 + 1);  // Choose one from 1 To 6 The random number
 
   if   (isNaN(userNumber)) {
     reject( new   Error( "Wrong Input Type" ));  // When the value entered by the user is not a number , Throw an exception and call reject function
   }
 
   if   (userNumber === randomNumber) {
     // If equal , We give users 2 branch
     resolve({
       points: 2,
       randomNumber,
     });
   }  else   if   (
     userNumber === randomNumber - 1 ||
     userNumber === randomNumber + 1
   ) {
     // If userNumber And randomNumber Difference between 1, So we give users 1 branch
     resolve({
       points: 1,
       randomNumber,
     });
   }  else   {
     // Otherwise, users have to 0 branch
     resolve({
       points: 0,
       randomNumber,
     });
   }
});

below , Let's create another function to ask if the user wants to continue the game :

1
2
3
4
5
6
7
8
9
const continueGame = () => {
   return   new   Promise((resolve) => {
     if   (window.confirm( "Do you want to continue?" )) {  // Ask the user if you want to continue the game
       resolve( true );
     }  else   {
       resolve( false );
     }
   });
};

In order not to force the end of the game , We created Promise Not used Reject Callback .

below , We create a function to handle the number guessing logic :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const handleGuess = () => {
   enterNumber()  // Return to one Promise object
     .then((result) => {
       alert(`Dice: ${result.randomNumber}: you got ${result.points} points`);  // When resolve Runtime , We get user scores and random numbers
       
       // Ask the user if you want to continue the game
       continueGame().then((result) => {
         if   (result) {
           handleGuess();  // If yes, The game goes on
         }  else   {
           alert( "Game ends" );  // If no, Pop up the end of the game box
         }
       });
     })
     . catch ((error) => alert(error));
};
 
handleGuess();  // perform handleGuess function

 

Here, when we call handleGuess Function time ,enterNumber() Return to one Promise object .

If Promise Status as resolved, We call then Method , Inform users of the results and scores of the quiz , And ask the user whether to continue the game .

If Promise Status as rejected, We will display a message that the user entered the error .

however , This code can solve the problem , But it's still a little difficult to read . Let's use async/await Yes hanldeGuess refactoring .

Online for async/await There are a lot of explanations for , Here I want to use a simple and general statement to explain :async/await It can turn complex asynchronous code into syntax sugar of class synchronous syntax .

Let's take a look at the refactored code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const handleGuess = async () => {
   try   {
     const result = await enterNumber();  // Instead of then Method , We just need to await Put it in promise front , You can get the results directly
 
     alert(`Dice: ${result.randomNumber}: you got ${result.points} points`);
 
     const isContinuing = await continueGame();
 
     if   (isContinuing) {
       handleGuess();
     }  else   {
       alert( "Game ends" );
     }
   }  catch   (error) {  // catch The method can be made by try, catch Function to replace
     alert(error);
   }
};

By using async keyword , We created an asynchronous function , The method used in the function is as follows :

  • and then Functions are different , We just need to await Keywords in Promise front , You can get the results directly .
  • We can use try, catch Grammar instead of promise Medium catch Method .

Here is the complete code after our refactoring , For reference :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const enterNumber = () => {
   return   new   Promise((resolve, reject) => {
     const userNumber = Number(window.prompt( "Enter a number (1 - 6):" ));  // Ask the user for a number
     const randomNumber = Math.floor(Math.random() * 6 + 1);  // The system randomly selects one 1-6 The number of
 
     if   (isNaN(userNumber)) {
       reject( new   Error( "Wrong Input Type" ));  // If the user inputs a non numeric error
     }
 
     if   (userNumber === randomNumber) {  // If the user guesses the number correctly , To the user 2 branch
       resolve({
         points: 2,
         randomNumber,
       });
     }  else   if   (
       userNumber === randomNumber - 1 ||
       userNumber === randomNumber + 1
     ) {  // If userNumber And randomNumber Difference between 1, So we give users 1 branch
       resolve({
         points: 1,
         randomNumber,
       });
     }  else   {  // Incorrect , have to 0 branch
       resolve({
         points: 0,
         randomNumber,
       });
     }
   });
};
 
const continueGame = () => {
   return   new   Promise((resolve) => {
     if   (window.confirm( "Do you want to continue?" )) {  // Ask the user if you want to continue the game
       resolve( true );
     }  else   {
       resolve( false );
     }
   });
};
 
const handleGuess = async () => {
   try   {
     const result = await enterNumber();  // await Replaced the then function
 
     alert(`Dice: ${result.randomNumber}: you got ${result.points} points`);
 
     const isContinuing = await continueGame();
 
     if   (isContinuing) {
       handleGuess();
     }  else   {
       alert( "Game ends" );
     }
   }  catch   (error) {  // catch The method can be made by try, catch Function to replace
     alert(error);
   }
};
 
handleGuess();  // perform handleGuess function

We have completed the second example , Let's start with a third example .

Example 3: from Web API Get country information from

Generally speaking, it should be from API When getting data from , Developers will use Promises. If a new window opens in https://restcountries.eu/rest/v2/alpha/cn, You'll see JSON Country data in format .

By using Fetch API, We can easily get the data , Here's the code :

1
2
3
4
5
6
7
8
9
const fetchData = async () => {
   const res = await fetch( "https://restcountries.eu/rest/v2/alpha/cn" ); // fetch() returns a promise, so we need to wait  for   it
 
   const country = await res.json();  // res is now only an HTTP response, so we need to call res.json()
 
   console.log(country);  // China's data will be logged to the dev console
};
 
fetchData();

Now we have the country we need / Regional data , Let's turn to the last task .

Example 4: from Web API To get a list of countries around a country

Below fetchCountry Function from example 3 Medium api Access to country information , The parameters are alpha3Code It refers to the country code of the country , Here's the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Task 4: Get information about China's neighboring countries
const fetchCountry = async (alpha3Code) => {
   try   {
     const res = await fetch(
       `https: //restcountries.eu/rest/v2/alpha/${alpha3Code}`
     );
 
     const data = await res.json();
 
     return   data;
   }  catch   (error) {
     console.log(error);
   }
};

Let's create a fetchCountryAndNeighbors function , By passing cn As alpha3code To get information about China .

1
2
3
4
5
6
7
const fetchCountryAndNeighbors = async () => {
   const china= await fetchCountry( "cn" );
 
   console.log(china);
};
 
fetchCountryAndNeighbors();

In the console , Let's look at the object content :

In the object , There is one border attribute , It's from China's neighboring countries alpha3codes list .

Now? , If we try to get information from neighboring countries by .

1
2
const neighbors =
     china.borders.map((border) => fetchCountry(border));

neighbors It's a Promise An array of objects .

When dealing with an array of Promise when , We need to use Promise.all.

1
2
3
4
5
6
7
8
9
10
11
const fetchCountryAndNeigbors = async () => {
   const china = await fetchCountry( "cn" );
 
   const neighbors = await Promise.all(
     china.borders.map((border) => fetchCountry(border))
   );
 
   console.log(neighbors);
};
 
fetchCountryAndNeigbors();

In the console , We should be able to see the country / List of regional objects .

Here is an example 4 All the code for , For your reference :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const fetchCountry = async (alpha3Code) => {
   try   {
     const res = await fetch(
       `https: //restcountries.eu/rest/v2/alpha/${alpha3Code}`
     );
     const data = await res.json();
     return   data;
   }  catch   (error) {
     console.log(error);
   }
};
 
const fetchCountryAndNeigbors = async () => {
   const china = await fetchCountry( "cn" );
   const neighbors = await Promise.all(
     china.borders.map((border) => fetchCountry(border))
   );
   console.log(neighbors);
};
 
fetchCountryAndNeigbors();

summary

Finish this 4 After samples , You can see Promise Useful when dealing with asynchronous operations or things that don't happen at the same time . I believe that in constant practice , The deeper you understand it 、 The stronger , I hope this article can understand Promise and Async/Await Bring some help .

Here is the code used in this article :

https://files.cnblogs.com/files/powertoolsteam/Promise-Async-Await-main.zip

版权声明
本文为[Grape City technical team]所创,转载请带上原文链接,感谢
https://javamana.com/2020/12/20201211085421412q.html

  1. redis 监控的一些构思
  2. Some ideas of redis monitoring
  3. Spring中获取request的几种方法,及其线程安全性分析
  4. Several methods of getting request in spring and its thread security analysis
  5. 20分钟带你掌握JavaScript Promise和 Async/Await
  6. 20 minutes to master JavaScript promise and async / await
  7. Mybatis - introduction, simple entry program
  8. Java Concurrent Programming: concurrent HashMap
  9. Mybatis: one to one association query
  10. Java IO
  11. Deep understanding of Java generics
  12. Object oriented [day07]: review of knowledge points (11)
  13. Chapter 2 spring
  14. Process of building minicube in local k8s environment
  15. HTTP header cache control (difference between request and response)
  16. Interpretation of jQuery source code
  17. The function of generating MD5 based on OpenSSL in C under Linux
  18. Making web full screen effect with jquery
  19. Notes on Python basic syntax (compared with Java)
  20. Java 7 exception handling new features - address suppressed () method
  21. Deep understanding of static keyword in Java
  22. Spring 4 uses websocket
  23. Using openldap to answer questions and using java to complete LDAP authentication
  24. Implementation of MySQL high availability cluster with corosync + pacemaker and DRBD
  25. Spring Data MongoDB example with Spring MVC 3.2
  26. Java production of a simple tank war
  27. Design pattern day02
  28. Hadoop pseudo Distributed installation and running test example
  29. Java Concurrent Programming: callable, future and futuretask
  30. Understanding the three characteristics of Java encapsulation
  31. Understanding closure of JavaScript
  32. Java set excel worksheet to read only
  33. Distributed Java service platform baratine
  34. Java barcode generation technology barcode4j
  35. Use springboot + MySQL + JPA to add, delete, change, query and page the database
  36. Distributed services framework Dubbo / dubbox getting started example
  37. Zookeeper notes (1) installation, deployment and hello world
  38. Oracle database trigger Usage Summary
  39. MySQL master replication with slave server