es6 study notes (2)

10.json

1. JSON object

  • JSON.stringify(): Turn the json object into a string
    Example:
    let a={a:5,b:3};
    console.log(JSON.stringify(a));
    Result:
    insert image description here

  • JSON.parse(): convert json string into json object
    example:
    let b='{"a":1,"b":2,"c":3}';
    console.log(JSON.parse(b));
    result:
    insert image description here

2. Shorthand

  • The attribute name is the same as the attribute value, just keep one for your own use
  • Method: ":function" block delete
    show() { }is equivalent toshow :function() { }

3. The standard way of writing json:

  • 1. Only double quotes can be used
  • 2. All attribute names must be wrapped in double quotes
    For example:
    {a:5,b:3} ×
    {"a":5,"b":3} √

11.promise

  • Supplement:
    Asynchronous: There is no relationship between operations, and multiple operations are performed at the same time.
    Disadvantages: complex code
    Synchronization: only one thing can be done at the same time.
    Advantages: simple code
  • Promise - Eliminate asynchronous operations and write asynchronous code in a synchronous manner.
  • Some methods of promise:
    Promise.all()
    The parameter is an array, and Promise.all can wrap multiple Promise instances into a new Promise instance. At the same time, the return values ​​of success and failure are different. When it succeeds, it returns a result array, and when it fails, it returns the value that was rejected first.
    Promise.race()
    The parameter is an array, and Promse.race means race, which means that whichever result in Promise.race([p1, p2, p3]) is obtained quickly, that result will be returned, regardless of whether the result itself is in a successful state or a failed state.
    The parameter is an array
  • Example 1:
    arr.txt
    insert image description here
    json.txt
    insert image description here
    Promise.html
function createPromise(url){
    
    
	return new Promise(function(reslove,reject){
    
    
	var xhr=new XMLHttpRequest();
	xhr.onreadystatechange=function(){
    
    
		if(xhr.readyState==4&&xhr.status==200){
    
    
			reslove(xhr.responseText);
		}
	}
    xhr.open('GET',url);
	xhr.send();
 })
}
var p=createPromise('arr.txt');
var p2=createPromise('json.txt');
p.then(function(arr){
    
    
	console.log(arr);
})
p2.then(function(json){
    
    
	console.log(json);
})

结果
insert image description here
Example two:
Promise.html

function createPromise(url){
    
    
	return new Promise(function(reslove,reject){
    
    
	var xhr=new XMLHttpRequest();
	xhr.onreadystatechange=function(){
    
    
		if(xhr.readyState==4&&xhr.status==200){
    
    
			reslove(xhr.responseText);
		}
	}
    xhr.open('GET',url);
	xhr.send();
 })
}
Promise.all([
	createPromise('arr.txt'),
	createPromise('json.txt')
]).then(function(arg){
    
    
	let [arr,json]=arg;
	console.log('arr的类型为:'+typeof(arr)+',结果:'+arr);
	console.log('json的类型为:'+typeof(json)+',结果:'+json);
})

结果
insert image description here

12.generator

1. Meaning: The generator is actually equivalent to a function.
Kick one step at a time.
Cannot be written as an arrow function.
Applicable scenarios: some asynchronous requests, such as sending ajax requests, etc., need to proceed to the next step after the request is successful, and then need to pause.
2. Ordinary functions - all the way to the end
generator function - can stop in the middle
3. For example:
js

function show(){
    
    
	console.log('a');
	console.log('b');
}
show();

result:
insert image description here
es6

function *show(){
    
    
	console.log('a');
	yield;
	console.log('b');
}
let genObj=show();
genObj.next();

Result:
insert image description here
4. How does generator() realize step by step?
Essentially, a generator() function is used to generate many small functions.
For example:
function *show(){
console.log('a');
yield;
console.log('b');
}
actually produces:
function show_1(){
console.log('a')
}

function show_2(){
console.log('b')
}

And proceeding
genObj.next();
genObj.next();
is actually equivalent to:
show_1();
show_2();

13.generator-yield

1. You can pass parameters.
Example 1:

function *show(){
    
    
	console.log('a');
	let f=yield;
	console.log(f);
	console.log('b');
}
var gen=show();
gen.next(12);
gen.next(5);
//结果为:
//a
//5
//b

Why is the value printed out for the second one 5?
insert image description here
gen.next(12) executes step 1, and
gen.next(5) executes step 2. The assignment of f is in step 2, so the result of f is 5.
This also shows that the first next cannot pass parameters to yield. So how to pass parameters in step 1?
Pass in the generator function. For example: var gen=show(99,88);
2. Can return
Example 2:

function *show1(){
    
    
	console.log('a');
	yield 12;
	console.log('b');
}
var gen1=show1();
let res1=gen1.next();
let res2=gen1.next();
console.log(res1,res2);

The result is: insert image description here
It can be seen that yield is followed by the data of the return value executed in the first step of the show1 function. In this way, the first step to execute the function can receive an object. The value of the object is exactly this parameter, and its done attribute indicates whether the show1 function has been executed.
If you want to execute the function in the last step, you can receive a value. Just add it at the end of the show1 function return xxx;.

3. Image understanding
Let's take a look at such an interesting example: About cooking:
insert image description here
expressed in pseudocode:
insert image description here
4. Comprehensive advanced
Example 3:

function *show1(){
    
    
	console.log('a');
	let a=yield 12;
	console.log(a);
}
var gen1=show1();
let res1=gen1.next();
let res2=gen1.next(res1.value);

The result is:
insert image description here
Explanation and expansion:
let a=yield(12);This line of statement cannot be understood as suspending the operation first, and then directly assigning the value of 12 to a. In fact, we need to remember: the value after yield is the return value of the first step function, and the value before yield is the parameter value of the second step function.
Therefore, it should be understood as: return to the value of the first step function after the first step is executed 12. When the second step is executed, the parameters of the second step function are passed a.

If the last step of the above code
let res2=gen1.next();
is changed to
insert image description here

14.generator instance——runner

1.txt in the data directory
[{"name":"张三",age:18},{"name":"李四",age:32},{"name":"王五",age:25}]
2.txt in the data directory The runner.js
[12,34,66,90,4,7,8]
in the data directory
{"fruit":"apple",price:5}
is installed through cnpm i yield-runner-blue, and each step is actually executed recursively.
ajax.js is a simple encapsulation request of native js
. Main code:

//ajax.js
function ajax(obj){
    
    
	var async=obj.async||true;
	return new Promise(function(reslove,reject){
    
    
		var xhr=new XMLHttpRequest();
		xhr.onreadystatechange=function(){
    
    
			if(xhr.readyState==4&&xhr.status==200){
    
    
				reslove(xhr.responseText);
			}
		}
		if(obj.type=="get"){
    
    
		    xhr.open("get",obj.url+"?"+obj.data,async);
		    xhr.send(null);
		}else if(obj.type=="post"){
    
    
		    xhr.open("post",obj.url,async);
		    xhr.setRequestHeader("Content-Type","application/X-www-form-urlencoded");
		    xhr.send(obj.data);
		}
	}).then(function(data){
    
    
		return data;
	})
}
<script src="runner.js"></script>
<script src="ajax.js"></script>
<script type="text/javascript">
		runner(
			function *(){
    
    
				let data1=yield ajax({
    
    url:'data/1.txt',type:'get'});
				let data2=yield ajax({
    
    url:'data/2.txt',type:'get'});
				let data3=yield ajax({
    
    url:'data/3.txt',type:'get'});
			    console.log(data1+'\n'+data2+'\n'+data3);
			}
		)
</script>

result:
insert image description here

15.generator instance——KOA

You need to open the mysql database and the server.js server at the same time.
Examples are as follows:

//server.js
const koa=require('koa');
const mysql=require('koa-mysql');
let server=new koa();
let db=mysql.createPool({
    
    
	host:'localhost',
	user:'root',
	password:'xxx',
	database:'test'    //test为数据库名
})
server.use(function *(){
    
    
	let data=yield db.query(`SELECT * from websites`);//websites为数据表名
	this.body=data;
})
server.listen(8080);

The result is:
insert image description here

16. ES7 preview

1. The meaning of array includes
: whether something is contained in the array, the return value is true/false

let arr=[12,34,55,77];
console.log(arr.includes(33));
//结果为:false

2. Array for...of

array JSON
for…in Subscript (key) key
for…of value x (JSON object is not an iterable object)

The for...of of the array mainly loops
the key => take out all the keys
values ​​=> take out all the values
​​entries => take out all the key-value
pairs 3. Numerical exponentiation
using operators **
3**8is quite 4. Math.pow(3,8)
The string
padStart()/padEnd() specifies the width, if it is not enough, fill in spaces or specify characters.
for example:

let str="555";
console.log('('+str.padStart(5,'0')+')');
console.log('('+str.padEnd(5,'0')+')');

The result is:
insert image description here
5. Tolerance

  • [1, 2, 3,] The old array cannot have a comma at the end, but the new one can
  • The comma at the end of the function parameter is also ok

6.async await
For example:

async function readData(){
    
    
	let data1=await ajax({
    
    url:'data/1.txt',type:'get'});
	let data2=await ajax({
    
    url:'data/2.txt',type:'get'});
	let data3=await ajax({
    
    url:'data/3.txt',type:'get'});
	console.log(data1+'\n'+data2+'\n'+data3);
}
readData();

It is basically the same as generator yield, which is equivalent to:

runner(
		function *(){
    
    
			let data1=yield ajax({
    
    url:'data/1.txt',type:'get'});
			let data2=yield ajax({
    
    url:'data/2.txt',type:'get'});
			let data3=yield ajax({
    
    url:'data/3.txt',type:'get'});
		    console.log(data1+'\n'+data2+'\n'+data3);
		}
	)

Two points that it is more advanced than generator yield are:

  • It does not depend on the external runner - unity, performance
  • Arrow functions can be used

17. Asynchronous operation

Asynchronous operations want to achieve synchronous fetching of data. There are four ways:
1. Callback
2. Promise
3. generator
4. async
If there are three ajax requests in total, and the next step can only be executed after the previous step is successful, here use native js to encapsulate ajax. The following is the pseudocode of these functions:

  • callback writing
	ajax({
    
    
			url:'xxxx',
			type:'get',
			data:'...',
			success:function(data1){
    
    
				ajax({
    
    
					url:'xxxx',
					type:'get',
					data:data1.value,
					success:function(data2){
    
    
						ajax({
    
    
							url:'xxxx',
							type:'get',
							data:data2.value,
							success:function(data3){
    
    
								//事情干完了
							},
							fail:function(){
    
    
								console.log('出错了');
							}
						})
					},
					fail:function(){
    
    
						console.log('出错了');
					}
				})
			},
			fail:function(err){
    
    
				console.log('出错了');
			}
		})
  • Prom
Promise.all([
ajax({
    
    url:'xxxx',type:'get',data:'...'}),
	ajax({
    
    url:'xxxx',type:'get',data:'...'}),
	ajax({
    
    url:'xxxx',type:'get',data:'...'}),
]).then(reslut=>{
    
    
	//事情干完了
},err=>{
    
    
	console.log('出错了');
})
  • generator
runner(
	function *(){
    
    
		let data1=yield ajax({
    
    url:'xxxx',type:'get',data:'...'});
		let data2=yield ajax({
    
    url:'xxxx',type:'get',data:'...'});
		let data3=yield ajax({
    
    url:'xxxx',type:'get',data:'...'});
	}
)
  • async
    has been mentioned in the ES7 preview.

And in the case of logic:
the format of the genetator is no different from synchronization.
Promise.all() processes a bunch at a time.
Of course, we can also choose new promsie(reslove,reject){}.then() to write.

Guess you like

Origin blog.csdn.net/qq_44875145/article/details/104614298