This is the 19th day of my participation in the Genwen Challenge

Picking up where we left off on the use of Promises, one of the methods the front end uses to handle asynchronous callbacks is Async/Await. It can be said that Async/Await is an upgraded version of Promise, and in the case of an Async/Await request being applied, the code can be made to look like a synchronous call resolving an asynchronous callback.

Before ES7, knowing that Promises were ES6’s solution to asynchronous callbacks and avoid Callback Hell, why did ES7 introduce a new Async/Await standard? The answer: Promise solved the asynchronous nesting problem by using a clear chain; However, if there are a lot of asynchronous requests somewhere in the actual development process, and the process is complex and nested, it can be awkward to examine the relevant code.

What is Async/Await?

Async/Await is based on Promise. Async/Await is interdependent and indispensable. They come out for Promise, which is also an evolutionary and improved version of Promise. This is to solve the asynchronous problem mentioned at the beginning of the article if a large number of complex nested promises are not easy to read.

1. Basic meaning of Async/Await

  1. Async/Await is based on Promise implementation and is a new way to write asynchronous code. They cannot be used for normal callback functions;
  2. Async/Await is also non-blocking;
  3. Writing Async/Await makes asynchronous code look like synchronous code, concise and easy to read.

Async/Await syntax

Async must declare a function and await must be used inside the async declared function. This is a fixed match. If any type of async does not meet the two conditions, the program will report an error.

      let data = 'data'
	a = async function () {
    		const b = function () {
        	   await data
    		}
	}
Copy the code

2. Nature of Async/Awaitd

1. The nature of Async

Async is another syntactic sugar wrapper for generator, which helps to realize generator invocation and makes the statement more similar to the expression of synchronous code. Async functions can be regarded as promise objects encapsulated by multiple asynchronous operations.

The return of an async declared function is actually a Promise, that is, as long as the declared function is async, no matter how it is handled internally, it must return a Promise, as shown in the following example:

(async function () {return 'Promise+++'})(Copy the code

2. The nature of Awaitd

The essence of await is syntactic sugar that provides the ability to wait for asynchronous return equivalent to “synchronous effect”, i.e. syntactic sugar for THEN. If you want to perform an asynchronous operation with await, the calling function must be declared with async.

Await can return a Promise object as well as a value. If await returns a Promise object, then we can continue to use the then function on the return value of await. Here’s an example:

Const a = async ()=>{let message = 'declare value 111' let result = await message; Console. log(' Wait for a while 'because the above program hasn't finished executing '); Return result} a(). Then (result=>{console.log(' output ',result); })Copy the code

3. Advantages of Async/Await

Why is Async/Awaitd better than Promise? The specific reasons are as follows.

1. Be concise

As can be seen from the above examples of Async/Awaitd, Async/Awaitd is very simple to write. Compared with Promise, it does not need to write. Then, it does not need to write anonymous functions to handle Promise’s resolve value, nor define redundant data variables, and it avoids the operation of nested codes. Greatly save a lot of lines of code, making the code handling asynchronous operation concise, easy to consult and precise positioning.

2. Error handling

Parse will need to use. Catch in promises, but the code for error handling will be very redundant. Be aware that code is more complex in practice than it should be in theory.

Parse can handle json.parse errors with try/catch using Async/Await, as shown in the following example:

                 const request = async () => {
        		try {
            		const data = JSON.parse(await getJSON())
            		console.log(data)
        		} catch (err) {
            		console.log(err)
        		}
    	         }
Copy the code

3. Conditional statements

By using Async/Await, conditional statements can be written concisely and code readability can be improved. Here, I will not give a comparison example, but just one example of using Async/Await:

       const request = async () => {
  		const data = await getJSON()
  		if (data.anotherRequest) {
    			const moreData = await anotherRequest(data);
    			console.log(moreData)
    			return moreData
 		 } else {
    			console.log(data)
    			return data    
  		}
	}
Copy the code

4. Median

In actual development, this scenario is used: call promisE1, use the results returned by PromisE1 to call Promise2, and then use the results of both to call promise3. Before Async/Await is used, it should look like this:

const request = () => { eturn promise1() .then(value1 => { return promise2(value1) .then(value2 => { return Promise3 (value1, value2)})})} with Async/Await:  const request = async () => { const value1 = await promise1() const value2 = await promise2(value1) return promise3(value1, value2) }Copy the code

From the above two writing methods, it can be seen intuitively that using Async/Await will make the code very clean, simple, intuitive and highly readable.

5. Error stack comparison

If multiple promises are called in the instance and one of them is wrong, the error stack returned in the Promise chain does not show the specific location of the error, which will lead to the time-consuming time of troubleshooting and difficulty of solving the error, and even have an adverse effect. Assume that the only function of the error stack is named errorPromise. But it’s not directly related to errors. If Async/Await is used, the error stack will directly point to the function where the error is located, so that it is more clear and intuitive for troubleshooting. Especially, it is very effective and useful when viewing the analysis error log.

6, debugging,

According to the advantages of Async/Await described above, it has been repeatedly emphasized that Async/Await will make the code concise and clear. In fact, in the debugging process, Async/Await can also make the code debugging easy and simple. Compared with Promise, there is no need to write too many arrow functions. You can step directly as if debugging synchronized code, skipping the await statement.

7. Interrupt/terminate the program

The Promise itself is only a state machine, storing three states. Once a request is issued, it must be closed and cannot be canceled. Even the pending state mentioned above is only a state of pending request, but not canceled.

When Async/Await is used, it is very easy to terminate the program. That is because Async/Await is semantically obvious. It is similar to normal function writing. Essentially, it just returns a Promise. Specific examples are as follows:

let count = 3; const a = async ()=>{ const result = await delay(2000); const result1 = await delaySecond(count); if (count > 2) { return ''; // return false; // return null; } console.log(await delay(2000)); The console. The log (" end "); }; a().then(result=>{ console.log(result); }) .catch(err=>{ console.log(err); })Copy the code

The async function essentially returns a Promise.

Four, the actual development process of asynchronous operations need to pay attention to matters

Async/Await using for loop to get data (serial)

According to the for loop of the above Promise to get data for comparison, directly use the scenario of the above instance to have a look at the writing of Async/Await, the specific operation is as follows:

       (async ()=>{
    		array = [timeout(2000), timeout(1000), timeout(1000)]
    		for (var i=0; i < array.length; i++) {
        			result = await array[i]();
        			console.log(result);
    		}
	})()
Copy the code

By contrast, I will also praise Async/Await here. Intuitively, we can see the same demand. Is it very convenient and concise to use Async/Await to achieve it?

The above is all the content of this chapter. Welcome to pay attention to the wechat public account of Sanzhan “Program Ape by Sanzhan”, and the Sina Weibo account of Sanzhan “Sanzhan 666”, welcome to pay attention!