async/await

1.Async/Await Introduction

With async/await, you can easily do what the previous promises do, it has the following characteristics:
• async/await is based on Promise and is not used for normal callback functions.
• async/await, like Promise, is non-blocking.
• async/await makes asynchronous code look like synchronous code, which is where its magic lies.
If a function adds async , the function will return a Promise

async function async1() {
  return "1"
}
console.log(async1()) // -> Promise {<resolved>: "1"}

async1().then(function(data){
     Console.log(data);  // -> 1
});

Calling three files in turn, the example is written in async/await, which can be implemented in just a few sentences.

var fs = require('fs');

function read(file) {
  return new Promise(function(resolve, reject) {
    fs.readFile(file, 'utf8', function(err, data) {
      if (err) reject(err)
      resolve(data)
    })
  })
}
async function readResult(params) {
  try {
         Var p1 = await read(params, 'utf8')//await followed by a Promise instance
    var p2 = await read(p1, 'utf8')
    var p3 = await read(p2, 'utf8')
    console.log('p1', p1)
    console.log('p2', p2)
    console.log('p3', p3)
    return p3
  } catch (error) {
    console.log(error)
  }
}
 readResult('1.txt').then( // async function returns a promise
  data => {
    console.log(data)
  },
  err => console.log(err)
)

2.Async/Await concurrent request

If you request two files, it doesn't matter, you can pass the concurrent request.

var fs = require('fs');

function read(file) {
  return new Promise(function(resolve, reject) {
    fs.readFile(file, 'utf8', function(err, data) {
      if (err) reject(err)
      resolve(data)
    })
  })
}
function readAll() {
  read1()
  Read2 () / / this function synchronous execution
}
async function read1() {
  let r = await read('1.txt','utf8')
  console.log(r)
}
async function read2() {
  let r = await read('2.txt','utf8')
  console.log(r)
}
readAll();

3. Async/await refactors the user management system data persistence operation code (ie database operation) 3, summary

1.JS asynchronous programming evolution history: callback -> promise -> generator -> async + await
2. The implementation of the async/await function is to wrap the Generator function and auto-executor in a function.
3.async/await can be said to be the ultimate asynchronous solution.
(1) The advantage of the async/await function over Promise is that:
• Handle the call chain of then to write the code more clearly and accurately
• It also elegantly solves the callback hell problem.
Of course, the async/await function also has some drawbacks, because await transforms asynchronous code into synchronous code. If multiple asynchronous code has no dependencies, using await will result in performance degradation. If the code has no dependencies, you can use the Promise.all method.

Intelligent Recommendation

Database SQL combat 1: Find all the information of the latest employees

thought: The topic asks to find all the information of the latest employees. Through a sub-query (select max(hire_date) from employees), find the latest hire time of the employee, hire_date, and then ...

Correction of TOPSIS model based on entropy weight method

Recently, I am learning mathematical modeling and found a very good course on B station. It is very comprehensive and all the algorithms I often test involve:Qingfeng Mathematical Modeling This articl...

51nod longest common subsequence output path +

When x = 0 or y = 0 when f [x] [y] = 0 When a [x] = b [y] when f [x] [y] = f [x-1] [y-1] +1 When a [x]! = B [y] when f [x] [y] = max (f [x] [y-1], f [x-1] [y]) Note that the string 1 from the start, b...

Enumeration algorithm summary

I learned the enumeration algorithm in this section. The enumeration method is the nature of the problem itself, and all possible solutions are listed in one by one, and in the process of listed one b...

More Recommendation

Two value methods for Map of Java brushing knowledge points: keySet and entrySet, HashMap, Hashtable, TreeMap, LinkedHashMap, ConcurrentHashMap, Weak...

  The interface java.util.Map includes three implementation classes: HashMap, Hashtable, and TreeMap. Of course there are LinkedHashMap, ConcurrentHashMap, WeakHashMap.   Map is used to storeKey-value...

Everyday fresh items

Everyday fresh items - project preference Understand the e-commerce Web project development process Project demand analysis Page page Function map Deployment page Project framework Understand the e-co...

The easiest way: install opencv on windows platform python, that is to achieve import cv2 function

The following old method used before installed opencv, after reinstalling the system, reinstalled opencv according to the original method, and the result has always been reported: ImportError: Module ...

Matlab programming skills: reading and writing text files

Various text files are involved in MBD (model-based design), and the automated processing of text files can greatly improve work efficiency. This article briefly introduces the first step of processin...

Mysql opens a remote connection

1. Log in to Mysql cmd enter mysql -u root -pyoupassword (Input rule After you press Enter, you will be prompted to enter the password. Note that there may or may not be spaces before the user name, b...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top