All good things must come to an end

** This should be the last section of this series. ** The first two chapters focus on promises. Why focus on promises? Promise is harder to use than async await, and promise itself is not a syntactic candy. There are a lot of concerns about using async await when you have not mastered it. Async await has no such concerns and is easy to use and semantic is clear.

Basic preheating: Hello, JavaScript asynchronous programming —- understand the beauty of JavaScript asynchronous

Understanding the Beauty of Asynchrony: Promise and Async await

Understanding the Beauty of Asynchrony: Promise and Async await (2)

Now we are going to learn async await

It feels weird not to talk about the iterator pattern

Iterators are a basic pattern for the Java language. List and set structures have iterators built into them.

Javascript doesn’t have this effect (PS: ES6 provides sets, and iterators can be implemented), but we don’t use this pattern very much. The iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing the internal representation of the object.

So: An iterator is the ability to traverse the entire element without exposing the internal representation of the object

The core is: don’t expose the interior, can traverse the interior

Let’s implement a simple iterator

// Do not select deep copy content when fetching data.
// There are problems handling reference types
// This is just a simplification of the demo
function Iterdtor(arr){
	let data = [];
    if(!Array.isArray(arr)){
        data = [arr];
    }else{
        data = arr;
    }
    let length = data.length;
    let index = 0;
    // The core of the iterator is next
    // When next is called, the next item of the internal object will be printed
    this.next = function(){
    	let result = {};
    	result.value = data[index];
    	result.done = index === length- 1? true : false;
    	if(index ! == length){ index++;return result;
    	}
    	// Returns a string prompt when the content is gone
    	return 'data is all done'
    };
}
let arr = [1.2.3.4.5.6];
// Generate an iterator object.
let iterdtor = new Iterdtor(arr);
iterdtor.next()
iterdtor.next()
Copy the code

At this point, most people don’t understand why we’re talking about iterators.

The Generator returns an iterator after execution

Async functions are syntactic sugar for Generator

These two reasons are all at once useful for writing iterators.

Write a simple Generator function

function *Iterdtor(){
	console.log(1);
	yield '123';
	console.log(2);
	yield '234';
	console.log(3);
	return '345'
}
let iterator = Iterdtor();
Copy the code

When we talk about blocking, we think of synchronous waiting for a blocked thread to cause the page to lag, which is obviously not a very good thing, why use this kind of thing?

So what are the benefits of this obstructive approach?

In Generator functions, the iterator calls the next function and executes until it stops at a yield. After the next call to Next, the code continues to execute until the next yield representation. Without yield, we execute until the last return. (Without a return, we execute until the last return.

Code is like toothpaste. You squeeze it out, squeeze it out, squeeze it out, squeeze it out, squeeze it out.

So what would it be like to use Generator to handle asynchronous requests?

/ / pseudo code
let ajaxSign = false;
function *ajaxGetSomething(){
    ajaxSomethingOne().then(res= >{ajaxSign = true})
    yield
    ajaxSign = false;
    ajaxSomethingSecond().then(res= >{ajaxSign = true})}let iterator = ajaxGetSomething();
iterator.next();
while(ajaxSign){
    iterator.next()
}
Copy the code

What if asynchronous requests were implemented this way,

1: There is a flag indicating ajax request completion.

2: When the flag is true, ajax execution is complete and the next event is ready.

3: Continue blocking the code below when the flag is false and ajax execution is not complete.

4: When the first flag is true, execute next (), then find asynchronous code between yields, set the flag to false, and start doing the Ajax thing, blocking the rest.

5: Set the flag to true when ajax is done, and what started in 2 continues until the iterator is complete.

A vulgar while loop implementing a call to Next is not desirable (after all, pseudo-code)

This way let us experience another way of dealing with asynchronous, is blocked to perform multiple serial asynchronous tasks, so that we can feel the synchronous writing to writing asynchronous code that is not in the right time to get to the generation of asynchronous data, you block the thread, you finish before his execution, you can’t do anything operating values.

How to use async await

It’s pretty clear how to use them at this point, right

async function ajaxGetData(){
    xxxx
    dosomething()
    await ajaxGetDataFirst()
    dosomething()
    await ajaxGetDataSecond()
    dosomething()
    xxx
}
ajaxGetData()
Copy the code

At this point it is clear that we use async functions to handle asynchronous effects,

We do a few things, then wait for an asynchronous ajaxGetDataFirst event to complete, and then continue to do some things. At the second asynchronous Ajax request, ajaxGetDataSecond (), we start executing the blocking function. Wait for the asynchronous event to complete and continue. To use the await keyword is to tell the code below that you have to wait until I am finished to wait your turn. Understand? In short, await very much.

When can I use await? It is only used inside the async function body, and the scope is not inherited.

 new Promsie(async (resolve,reject)=>{
     await xxx
 })
 // Such async will make await effect, writing outside of promise will await error as above
Copy the code

Can await receive a synchronous thing? Continue execution without blocking

What is the return value of async? Async returns a Promise object,

???? What returns a Promise object. What’s the use of that? This means that you can continue to return the results you want in a Promise object after executing all the asynchronous requests. What does promise do? It seems to be able to store a value that triggers a callback function under specified conditions, so this helps us to throw data from an internal asynchronous request outside the function.

In a usage scenario, we sometimes need an asynchronous result, such as the result of an Ajax request. What if we want the asynchronous result? “Await” can help me get the result after performing an asynchronous operation and execute the result sequentially. Until I return and I return the result,

We can use either of the following

async function fn(){
	let result = await new Promise((resolve,reject) = >{
		setTimeout((a)= >{
            resolve(100)},10000)
	}).then(res= >{
			return res
		})
	return result
}
let a = fn()
Copy the code
async function fn(){
	let result = await new Promise((resolve,reject) = >{
		setTimeout((a)= >{
            resolve(100)},10000)})return result
}
let a = fn()
Copy the code

At this time, the results of asynchronous operations within async can be naturally thrown outside the function to be used, which can solve a lot of business encapsulation problems.

Difference between Async and Generator

What is the difference between Async and Generator?

Async is the syntactic sugar of Generator, which can be used to implement async. The core of using Generator to implement async is to implement such content without the next call, which IS what I will learn in the future (there is not enough time at present. I plan to write a special article after learning well to implement the following async.

The end!

This section does not talk much about async. Instead, it first introduces iterators, then Generator, and finally gives a brief introduction to the use of async. This is the order in which I learn async, and async is easy to use and familiar with synchronous writing. What is easy to use often means that there is something inside the method that you don’t know about, and that is what we want to explore AV8D!!!!

To summarize

We have understood the process of asynchronous program execution and the execution sequence conditions of event table, task queue, macro task and micro task. Understand the use of asynchronous promise, promise implementation mechanism, async usage, and derived iterator knowledge.

This period of time and while learning while producing articles, there is a feeling of being encouraged by everyone, ha ha ha ha. The word “spur” is a little strange. During this process, I found that learning should not only be about interest. Interest can help you study the content you like, which has infinite power.

In the past, asynchronism was the worst part for me to master. I have gained a lot from this stage of learning. I wonder how much you, as a reader, have gained. Only you know that

There is an end and a beginning

Let’s leave the beauty of asynchrony behind.

The following is a huge series of chapters, I will carry on a systematic study of the Vuer-Router source code, and with the study of the output document yo, is to continue to spur and learn with you. Coder (boy and girl) you are never alone

I am a fresh graduate, recently maintained a public account with friends, the content is that we are in the transition from fresh graduate to the development of this way stepped on the pit, has been our step by step learning records, if interested in friends can pay attention to it, together with fuel ~