Node.js ES7 asynchronous function

Asynchronous functions are asynchronous programming syntax ultimate solution, it allows us to synchronize asynchronous code written form, so the code is no longer nested callback function, the code becomes clear.

 

Basic grammar:

const fn = async () => {}
async function fn () {}

 

// async
1. // in front of an ordinary function definition plus asynv keywords, common function becomes asynchronous function
// default return value of the function is asynchronous 2. promise target
// 3. Use keywords in internal asynchronous functions throw error thrown
4. // return keywords within an asynchronous function returns a result, the result will be wrapped in the promise object, instead of a return keyword promise method resolve.

// await keyword
// 1. It can only appear in asynchronous function
// 2. promise behind await objects can only promise to write, write, other types of API is not acceptable.
// 3. await keyword is suspended asynchronous function execution down until you promise to return results.
 
Example:
 1 async function f1 () {
 2   return 'f1'
 3 }
 4 
 5 async function f2 () {
 6   return 'f2'
 7 }
 8 
 9 async function f3 () {
10   return 'f3'
11 }
12 
13 async function run () {
14   let r1 = await f1()
15   let r2 = await f2()
16   let r3 = await f3()
17   console.log(r1)
18   console.log(r2)
19   console.log(r3)
20 }
21 
22 run()

 

Example 2:

. 1 const the require FS = ( 'FS' )
 2  // transformation of the API function asynchronous, it return promise objects, to support asynchronous function syntax 
. 3 const = promisify the require ( 'util' ) .promisify
 . 4  // call the method of retrofitting an existing promisify asynchronous API, allowing its return promise objects 
. 5 const = readFile promisify (fs.readFile)
 . 6  
. 7 the async function RUN () {
 . 8   the let the await readFile R1 = ( './ 1.txt', 'UTF8' )
 . 9   the let the await R2 = readFile ( './ 2.txt', 'UTF8' )
 10   the let the await readFile R3 = ( './ 3.txt', 'UTF8' )
 . 11  the console.log (R1)
 12 is  Console.
log(r2)
13  console.log(r3)
14 }
15 
16 run()

 

 

Guess you like

Origin www.cnblogs.com/liea/p/11221022.html