Deep Interpretation of ES6 Series

Keywords: Javascript JSON JQuery github

Preface from Lao Zeng es6:

  • Hello, buddies, Z is back again. Welcome to Super IT's blog time. In the previous section, we talked about string, object-oriented and json's knowledge. In this section, we continue the ocean of our knowledge and fight together without baldness!Insufficient Welcome Question Message.

    I swear I really don't have a P-chart_Unexpectedly, this series has been favored by the minor editors. It has been popular since the publication of this series. Shy, it makes people look red with old faces. That's all!I'll seriously finish this series and then take you on a project framework!Let's do things together!Let's start now!This section is the end of es6. Next section is about es789....

Promise

  • Old Zeng started his English teaching. What is promise? I'm a man of words. Don't mention four horses. Forty horses can't pull me back. So promise is what I will do. As for how long it will take to do it ~I will do it anyway.So what does promise have to do with our es6?Let's sell it first.
  • There are two things to mention here. I believe that a buddy with a certain foundation will know what I want to say, asynchronous and synchronous.
Two-step Feature 1 Feature 2
asynchronous There's nothing to do between operations, you can do more than one operation at a time Code is more complex
synchronization You can only do one thing at a time Simple code

So you certainly want to ask how asynchronous and synchronous projects work?What am I doing with it?Let me make an analogy:

The pictures, data, text data and so on are not written to death here, they need to be taken from the background. If you use asynchronous, it's like this code, which is also called callback to hell. This is scary. If you have hundreds of data, how can you survive? I don't know if you can survive or not, but I can't.

//callback-hell callback to Hell
getFileContent('a.json',data => {
    console.log("data",data)
    getFileContent(data.next, data2 =>{
        console.log('data2',data2)
        getFileContent(data2.next, data3 =>{
            console.log('data3',data3)
        })
    })
})

This is the time to call out our Promise. Its purpose is to eliminate asynchronous operations. What exactly is it?One sentence summary:

  • Write asynchronous code synchronously

How exactly does Promise work

  • Let's take an example of Ajax and say you don't know what to do with ajax. That's okay. Follow along, so you can see what I know about you. At least it doesn't affect code reading. After that, look back and see for yourself ajax tutorial You've got it all. That's the rubbish for now. First look at the directory structure:


  • Now, the question is, I want to request these two json files in index by ajax, and successfully print out the contents of the json inside. If it fails, it will pop up and fail. What do you want to do?One tip is the use of Promise.all:
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
   	<script>
   		let p1 = new Promise((resolve, reject) =>{
   			//Asynchronous Code
   			$.ajax({
   				url: 'dataA.text',
   				dataType: 'json',
   				success(arr) {
   					resolve(arr)
   				},
   				error(err) {
   					reject(err)
   				}
   			})
   		})
   		
   		let p2 = new Promise((resolve, reject) =>{
   			$.ajax({
   				url: 'dataB.text',
   				dataType: 'json',
   				success(arr) {
   					resolve(arr)
   				},
   				error(err) {
   					reject(err)
   				}
   			})
   		})
   		
   		Promise.all([
   			p1,p2
   		]).then((arr) =>{
   			let [resA,resB] = arr
   			alert("all success")
   			console.log(resA,resB)
   		},(err) =>{
   			alert("fails")
   			console.log(err)
   		})
   	</script>

Just see if the code has any understanding, don't worry about the code will continue to optimize, let's parse the code first, use arrow functions and deconstruct assignments are all what we said in the previous blog. Forget your kid's shoes and look at the old blog by yourself. Of course, I am also a warm man. Let's put a picture to annotate and parse for you:

  • resolve--Resolved, reject--Rejected
  • That's clear when you get to us, resolve succeeds, reject fails
    Figure 1, corresponding to the successful and failed execution of the request and the return:
  • Promise corresponds to the execution and return of success and failure, green to green, purple to purple, red to red, by the way, no matter what the request is or what the function fails must be executed to develop good habits, I did not like to write the return of failure before, honey confidence has no haha, will cause sometimes do not know the cause of the error.

    So I'm afraid you don't know p1,p2 yet. Would you like me to print it for you?(vii)After all, there's a comma in the code of p1,p2, console, but it's just covered by a line. Looking at the picture, you can see that it's a promise object:

    Now to simplify the code, I said, I am a lazy person, although p1 and p2 directly ctrl c+ctrl v would be good to change one more letter code, but I am too lazy to copy and paste, two big codes look at emm what, let's encapsulate a function:
<script>
	function createPromise(url){
		return new Promise((resolve, reject) =>{
			$.ajax({
				url: url,
				dataType: 'json',
				success(arr) {
					resolve(arr)
				},
				error(err) {
					reject(err)
				}
			})

		})
	}
	let p1 = createPromise("dataA.text")
	let p2 = createPromise("dataB.text")
	Promise.all([
		p1,p2
	]).then((arr) =>{
		let [resA,resB] = arr
		alert("all success")
		console.log(resA,resB)
	},(err) =>{
		alert("fails")
		console.log(err)
	})
</script>

Is that more refreshing? Of course, that's not enough. Can you still look like a better one?If you can't, follow along and see what the code prints out?

let p = $.ajax({url:'dataA.text',dataTape:'json'})
console.log(p)


We found that no jQuery returned a promise object of its own, so we don't need to use p1,p2 to receive a promise, just use it now:

<script>
	Promise.all([
		$.ajax({url:"dataA.text",dataType:'json'}),
		$.ajax({url:'dataB.text',dataTape:'json'})	
	]).then((arr) =>{
		console.log("success",arr)
	},(err) =>{
		console.log('fail',err)
	})
</script>

Does this make it much cooler?!!!

  • This is the perfect use of Promise. Promise.all must be fully successful before it can be executed, much like whether or not there is'and'. Here we refer to another, Promise.race, which means that one function will execute successfully if it comes first.

generator

Basic functions of generator

  • What is this?There is no search for poor English. Translation is the generator.What's this for?Make a comparison that's easy to understand.
  • Common function: All the way to the end - High-speed train
  • Geneor function: Stop-on-demand - taxi
    So let's see how this generator differs from the normal function.Look what it is that prints out?Guess?To tell the truth, I didn't know Haha at first_Here's a hint that yield translates to give up. We interpret him here as giving up temporarily.
<script>
	function *show(){
		alert('a');
		yield;
		alert('b')
	}
	show()
</script>

Do you think a pop-up will pop up? Didn't expect anything, and the console won't make a mistake. What should you do now?alert(show()) and console.log(show()) to see?

Alert tells you that execution is a generator object, but when we look inside alert, we will find that there is a next method in it, which is very important.

Let's show().next(); do it and see what it is?

So what if you want to show both a and b?Let's try this:

	let obj = show()
	obj.next();
	obj.next();


So A and B come out, and there's only b, so next feels like a kick, right.So how do you want to ask Lao Zeng how this generator works?You guess I told you not to say haha, of course.

  • The basic principle of generator here is to divide the original *show() function into two small functions, which, of course, you can't see, are divided into show1 and show2, each performing alert('a') and alert('b').

Elaborate yield

yield parameter

  • As we just said in the last point, yield means to give up temporarily, and you also have a basic understanding of Promise. So take a look at this code and you can guess what the result is?
<script>
	function *show(){
		alert('a');
		let a = yield;
		alert('b');
		alert(a);
	}
	let gen = show();
	gen.next(12);
	gen.next(5);
</script>



Here's the point!

5???Is there any doubt about life?Ha-ha I am very confused, said, let's analyze which two pieces of code are executed by two next s *show:


Whether the first next should be the code of a white box or not, when yield paused, the second next is the code of a yellow box.So it's not hard to understand that gen.next(5); is the value passed to someone, and see if the yellow box is the value passed to let a.

  • So what if you want to give the alert value in the white box above?
function *show(num1,num2){
		alert(`${num1} ${num2}`)
		alert('a');
		
		let a = yield;
		
		alert('b');
		alert(a);
	}
	let gen = show(9,99);
	gen.next(12);
	gen.next(5);


That's OK, so you can also see that the first next is useless for yield ing.

yield returns

*Come on, after we've finished talking about returning, the same thing about guessing what the result of code execution is?

<script>
	function *show(){
		alert('a');		
		yield 12;	
		alert('b');
		return 55;
	}
	let gen = show();
	let res1 = gen.next();
	console.log(res1)	
	let res2 = gen.next();
	console.log(res2)
</script>




Believe the wit, you have at least seen that done here is whether the execution is complete, so according to the previous understanding of white and yellow boxes, can you understand that returning value is 12 and 55?If we don't understand it yet, let's continue to look at it.

What on earth is yield

  • Let's get rid of the code here. Let's get a pseudocode for grounding gas. You come here:

    To put it plainly, it's like a division of work in a kitchen separated by yield. Everything you do is as simple as that, and you don't know the comments of your little buddy yet.

Instances of generator

  • After introducing generator, we also know its basic usage, so don't we mean it can also be used to eliminate asynchronous operations?So how exactly do you do that?
  • First we need a runner file. I'll put it on github. There's a GitHub link at the end of the article. You can see it in the folder 15 in es6. If you don't find a file, you can chat with me privately.(vii).
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script src="runner.js"></script>
<script>
	runner(function *(){
		let data1 = yield $.ajax({url:'dataA.text',dataType:'json'})
		let data2 = yield $.ajax({url:'dataB.text',dataType:'json'})
		let data3 = yield $.ajax({url:'dataC.text',dataType:'json'})
		console.log(data1,data2,data3)
	})
</script>

Corresponding dataA,B,C, one thing to note here is who the promise returned by our first $.ajax was returned to. We actually returned to runner to process and yield pause. After processing, we returned to data1 to continue execution. After processing, the second Ajax was given to data2, followed by data3.

Summary of asynchronous operations

Callback

//Callback
$.ajax({
  url: xxx,
  dataType: 'json'
  success(data1){
    $.ajax({
      url: xxx,
      dataType: 'json'
      success(data2){
        $.ajax({
          url: xxx,
          dataType: 'json'
          success(data3){
            //come to an end
          },
          error(){
            alert('Wrong');
          }
        });
      },
      error(){
        alert('Wrong');
      }
    });
  },
  error(){
    alert('Wrong');
  }
});

Promise

//Promise
Promise.all([
  $.ajax({url: xxx, dataType: 'json'}),
  $.ajax({url: xxx, dataType: 'json'}),
  $.ajax({url: xxx, dataType: 'json'})
]).then(results=>{
  //come to an end
}, err=>{
  alert('Wrong');
});

generator

//generator
runner(function *(){
  let data1=yield $.ajax({url: xxx, dataType: 'json'});
  let data2=yield $.ajax({url: xxx, dataType: 'json'});
  let data3=yield $.ajax({url: xxx, dataType: 'json'});
  //come to an end
});

Disadvantages of Promise

  • Looking at 11.2 and 11.3 above doesn't make much difference, really, but if promise has logic, like what if a user is logged in as vip, not VIP?What is our code like at this time?
//Logical-Promise
Promise.all([
  $.ajax({url: 'getUserData', dataType: 'json'})
]).then(results=>{
  let userData=results[0];
  if(userData.type=='VIP'){
    Promise.all([
      $.ajax({url: 'getVIPItems', dataType: 'json'})
    ]).then(results=>{
      let items=results[0];
      //Generate lists, display...
    }, err=>{
      alert('Wrong');
    });
  }else{
    Promise.all([
      $.ajax({url: 'getItems', dataType: 'json'})
    ]).then(results=>{
      let items=results[0];
      //Generate lists, display...
    }, err=>{
      alert('Wrong');
    });
  }
}, err=>{
  alert('fail');
});

I have a lot of days to see the normal callbacks, at this time I might as well use the normal callbacks to tell the truth.

//With logic-normal callback
$.ajax({url: 'getUserData', dataType: 'json', success(userData){
  if(userData.type=='VIP'){
    $.ajax({url: 'getVIPItems', dataType: 'json', success(items){
      //Generate lists, display...
    }, error(err){
      alert('Wrong');
    }});
  }else{
    $.ajax({url: 'getItems', dataType: 'json', success(items){
      //Generate lists, display...
    }, error(err){
      alert('Wrong');
    }});
  }
}, error(err){
  alert('Wrong');
}});

Normal callbacks are better than Promise, right, but with generator, let's see what it says?

//With logic-generator
runner(function *(){
  let userData=yield $.ajax({url: 'getUserData', dataType: 'json'});
  if(userData.type=='VIP'){
    let items=yield $.ajax({url: 'getVIPItems', dataType: 'json'});
  }else{
    let items=yield $.ajax({url: 'getItems', dataType: 'json'});
  }
  //Generate,...
});

Does this time feel that his advantage appears in a flash, just like our normal function execution, simple and rough.

Okay, here's what our ES6 says!!!!!!!!Finally, the four series are finished.

_____
All of you can see here, just to say that we really have a good relationship!Don't give a compliment._Do you want to pay attention to it? The little one who secretly collects my blog can see it behind the scenes. Give some support to the old one. Unsurprisingly, I have been hagging all the time since then. I am not in a hurry to learn and write a blog. I have a good foundation and start the project directly from 6 to fly.

The next section describes ES7 and later versions

Put on my main blog Blog ParkCSDNGitHubpipe

Posted by BoukeBuffel on Fri, 10 Apr 2020 11:54:16 -0700