前端打怪之旅=>Es6入门(Promise、集合)

60 阅读3分钟

Promise

Promise是ES6引入的异步编程的新解决方案.语法上Promise是一个构造函数,用来封装异步操作并可以获取其成功或失败的结果。

解决回调地狱的问题

        //实例化 Promise 对象
        const p = new Promise(function(reslove,reject){
            setTimeout(function(){
                // let data = '数据库的数据'
                
                //reslove 
                // reslove(data);
                
                let error = '数据读取失败'
                reject(error)
            },1000)
        })
        
        //调用promise对象的then方法
        p.then(function(value){
            console.log(value)
        },function(reason){
            console.log(reason)
        })

Promise读取文件

//1.引入 fs 模块
const fs = require('fs');
​
//2.调用方法
fs.readFile('./resource/a.md', (err, data)) => {
    //如果失败,则抛出错误
    if (err) throw err;
    //如果没出错,则输出内容
    console.log(data.toString)
}
​
//3.使用 promise 封装
const p = new Promise(function(reslove, reject) {
    fs.readFile('./resource/a.md', (err, data)) => {
        //判断如果失败
        if (err) reject(err);
​
        //如果成功
        reslove(data);
    }
})
​
​
p.then(function(value) {
    console.log(value.toString())
    },
    function(reason) {
        console.log('读取失败!')
    });

Promise封装ajax

//接口地址https://api.apiopen.top/getjoke
        
        const p =new Promise((reslove,reject)=>{
            //1.创建对象
            const xhr = new XMLHttpRequest();
            
            //2.初始化
            xhr.open("GET","https://api.apiopen.top")
            
            //3.发送
            xhr.send();
            
            //4.绑定事件,处理相应结果
            xhr.onreadystatechange = function(){
                //判断
                if(xhr.readyState == 4){
                    //判断响应状态码 200=>299
                    if(xhr.status>=200&&xhr.status<=299){
                        reslove(xhr.response);
                    }else{
                        //如果失败
                        reject(xhr.status)
                    }
                }
            }
        })
        
        //指定回调
        p.then(function(value){
            console.log(value);
        },function(reason){
            console.log(reason)
        })

Promise的catch

		const p = new Promise((resolve, reject) => {
				setTimeout(() => {
					//设置p对象的状态为失败,并设置失败的值
					reject("出错啦!");
				}, 1000)
			});
		//p.then(function(value) {}, function(reason) {
		//console.error(reason);
		//});
		p.catch(function(reason) {
			console.warn(reason);
		});

集合

set

ES6提供了新的数据结构Set(集合)。它类似于数组,但成员的值都是唯一的,集合实现了iterator接口,所以可以使用「扩展运算符」和「for.of」进行遍历,集合的属性和方法:

  • size 返回集合的元素个数
  • add 增加一个新元素,返回当前集合
  • delete 删除元素,返回boolean值
  • has 检测集合中是否包含某个元素,返回boolean值

声明及传参

        //声明一个 set
        let s1 = new Set();
        console.log(s1,typeof s1);
        let s2 = new Set(['小a','小b','小c','小d','小e','小a']);
        console.log(s2)
        //会自动去重
		console.log(s2.size);
		s2.add('小s');
		s2.delete('小c')
		console.log(s2.has('小e'))
		s2.clear()

交并补

let arr=[1,2,3,4,5,4,3,2,1]
			//1.数组去重
			let result=[...new Set(arr)];
			console.log(result);
			//2.交集
			let arr2=[4,5,6,5,6];
			let result = [...new Set(arr)].filter(item=>{
				if(s2.has(item)){
					return true;
				}else{
					return false;
					
			});
			let result = [...new Set(arr)].filter(item=>new Set(arr2).has(item))
			console.log(result)
			//3.并集
			let union =[new Set([...arr,arr2])]
			console.log(union)
			
			//4.差集
			let diff = [...new Set(arr)].filter(item =!(new Set(arr2).has(item)));
			console.log(diff);

Map

ES6提供了Map数据结构。它类似于对象,也是键值对的集合。但是“键的范围不限于字符串,各种类型的值(包括对象)都可以当作键。Map也实现了iterator接口,所以可以使用「扩展运算符」和「for...of.』进行遍历。Map的属性和方法:

1)size返回Map的元素个数

2)set增加一个新元素,返回当前Map

3)get返回键名对象的键值

4)has检测Map中是否包含某个元素,返回boolean值

5)clear清空集合,返回undefined

        //声明map
        let m = Map();
        //添加元素
        m.set('name','Lee');
        m.set('change',function(){
            console.log("我们可以改变你!!");
        });
        let key ={
            school :'浅辄'
        };
        m.set(key,['北京''上海''深圳]);
        
        //size
        /console.log(m.size);
        //删除
        m.delete('name');I
        
        console.log(m);