【ES6】进阶语法

目录

一、ES6模块化

ES6模块化的基本语法

二、Promise    解决回调地狱问题

Ⅰ.then()方法

Ⅱ.catch()方法

Ⅲ.all()方法 

Ⅳ.race()方法

三、async和await

四、EventLoop


一、ES6模块化

浏览器端和服务器端通用的模块化开发规范

        ①每个Js文件都是一个独立的模块

        ②导入其他模块使用import关键字

        ③向外共享模块成员使用export关键字

在node.js体验ES6模块化

        ①安装了v14.15.1或更高版本的node.js

        ②在vscode中使用命令 npm init -y可以初始化一个package.json的文件

        ③在该文件的根节点添加”type”: “module”节点


ES6模块化的基本语法

①默认导出与默认导入

        默认导出    export default 默认导出的成员

let n1=10;
function show(){};
export default {
    n1,
    show
}

                注意:每个模块中,只允许使用唯一的一次export default,否则会报错

        默认导入   import 接收名称 from ‘模块标识符’

import m1 from './01.js';
console.log(m1);

                注意:默认导入时,接受的名称可以任意名称,只要是合法的成员名称即可


②按需导出与按需导入

        按需导出   export 按需导出的成员

export let m1=10;
export let m2=20;
export function say(){};

                注意:每个模块中可以使用多次按需导出

        按需导入   import{s1}from ‘模块标识符’

import {m1,m2,say} from './02.js';
console.log(m1);  //10
console.log(m2);  //20
console.log(say); //[Function:say]

        注意:   按需导入的成员名称必须和按需导出的名称保持一致

                     按需导入时,可以使用as关键字进行重命名

import {m1,m2 as str2,say} from './02.js';
console.log(str2);  //20

                      按需导入可以和默认导入一起使用

//02.js
export let m1=10;
export let m2=20;
export function say(){};
export default {
    a:20
}
import info,{m1,m2,say} from './02.js';
console.log(info);  //{ a:20}

③直接导入并执行模块中的代码

        只想单纯执行某个模块中的代码,并不需要得到模块中向外共享的成员

        import ‘模块标识符’

//03.js
for(let i=0;i<3;i++){
    console.log(i);
}
import './03.js'

二、Promise    解决回调地狱问题

回调地狱       多层回调函数的相互嵌套

        代码耦合性太强,难以维护

        大量冗余的代码,可读性太差


①Promise是一个构造函数

        我们可以创建Promise实例 const p=new Promise()

        new出来的Promise实例对象,代表一个异步操作

②Promise.prototype上包含一个.then()方法

        每一次new Promise()构造函数得到的实例对象,都可以通过原型链的方式访问到.then()方法,例如p.then()

③.then()方法用来预先指定成功和失败的回调函数

        p.then(成功的回调函数,失败的回调函数)

        p.then(result=>{}.error=>{})

        调用.then()方法时,成功的回调函数是必选的,失败的回调函数是可选的


基于then-fs异步的读取文件的内容

Node.js提供的fs模块仅支持以回调函数的方式读取文件,不支持promise的调用方式。因此,需要安装then-fs第三方包,从而支持我们基于Promise的方式读取文件的内容

命令:npm install then-fs

调用then-fs提供的readFile()方法,可以异步的读取文件的内容,它的返回值是Promise的实例对象,因此可以调用.then()方法为每个Promise异步操作指定成功和失败之后的回调函数

import thenFs from 'then-fs';
//无法保证文件的读取顺序
thenFs.readFile('./files/1.txt','utf8').then(r1=>{console.log(r1);},er1=>console.log(err1.message))
thenFs.readFile('./files/2.txt','utf8').then(r2=>{console.log(r2);},er1=>console.log(err1.message))
thenFs.readFile('./files/3.txt','utf8').then(r3=>{console.log(r3);},er1=>console.log(err1.message))

Ⅰ.then()方法

        是Promise原型对象具有的

如果上一个.then()方法中返回了一个新的Promise实例对象,则可以通过下一个.then()继续处理。通过.then()方法的链式调用,解决了回调地狱的问题

import thenFs from 'then-fs';
//可以保证文件的读取顺序
thenFs.readFile('./files/1.txt','utf8')  //返回值是Promise实例对象
.then(r1=>{    //通过.then为第一个Promise实例指定成功的回调函数
    console.log(r1);
    return thenFs.readFile('./files/2.txt','utf8') //在第一个.then中返回一个新的Promidse实例对象
})
.then(r2=>{  //继续调用,为第一个.then的返回值指定成功的回调函数
    console.log(r2);
    return thenFs.readFile('./files/3.txt','utf8')//在第二个.then中再返回一个新的Promise实例对象
})
.then(r3=>{ 继续调用,为第二个.then的返回值指定成功的回调函数
    console.log(r3);
})

Ⅱ.catch()方法

        是Promise原型对象具有的

作用:捕获错误

不希望前面的错误导致后续的.then无法正常执行,可以将.catch的调用提前

.catch(err=>{
    console.log(err.message);
})

Ⅲ.all()方法 

        是Promise对象具有的

会发起并行的Promise异步操作,等所有的异步操作全部结束后才执行下一步的.then操作(等待机制)

Promise实例的顺序,就是最终结果的顺序

const promiseArr=[
    thenFs.readFile('./files/1.txt','utf8'), //111
    thenFs.readFile('./files/2.txt','utf8'), //222
    thenFs.readFile('./files/3.txt','utf8')  //333
]
Promise.all(promiseArr)
    .then(result=>{  
        console.log(result);  //['111','222','333']
})
.catch(err=>{
    console.log(err.message);
})

Ⅳ.race()方法

        是Promise对象具有的

发起并行的Promise异步操作,只要任何一个异步操作完成,就立即执行下一步的.then操作(赛跑机制)

const promiseArr=[
    thenFs.readFile('./files/1.txt','utf8'), //111
    thenFs.readFile('./files/2.txt','utf8'), //222
    thenFs.readFile('./files/3.txt','utf8')  //333
]
Promise.race(promiseArr)
    .then(result=>{    
        console.log(result);   //输出执行最快的文件的结果
})
.catch(err=>{
    console.log(err.message);
})

基于Promise封装异步读文件的方法

        ①方法的名称要定义为getFile

        ②方法接收一个形参fpath,表示要读取文件的路径

        ③方法的返回值为Promise实例对象

        ④在new Promise()构造函数期间,传递一个function函数,将具体的异步操作定义到function函数内部

        ⑤通过.then()指定的成功和失败的回调函数,可以在function的形参中进行接收

        ⑥Promise异步操作的结果,可以调用resolve或reject回调函数进行处理

import thenFs from 'then-fs';
function getFile(fpath){
    return new Promise(function(resolve,reject){
        fs.readFile(fpath,'utf8',(err,dataStr)=>{
            if(err) return reject(err)//读取失败,调用失败的回调函数
            resolve(dataStr)//读取成功,调用成功的回调函数
        })
    })
}
getFile('./files/1.txt').then(r1=>{
    console.log(r1),err=>{
        console.log(err.message);
    }
})

三、async和await

        ①如果在function内部使用了await,则function必须被async修饰

        ②在async修饰的方法中,第一个await之前的代码会同步执行,await之后的代码会异步执行

import thenFs from 'then-fs';
//根据顺序读取文件1,2,3内容
async function getAllFile(){
    const r1=await thenFs.readFile('./files/1.txt','utf8')
    console.log(r1);
    const r2=await thenFs.readFile('./files/2.txt','utf8')
    console.log(r2);
    const r3=await thenFs.readFile('./files/13.txt','utf8')
    console.log(r3);
}
getAllFile();
//输出顺序  A B C  111 222 333 D
import thenFs from 'then-fs';
console.log('A');
async function getAllFile(){
    console.log('B');
    const r1=await thenFs.readFile('./files/1.txt','utf8')
    const r2=await thenFs.readFile('./files/2.txt','utf8')
    const r3=await thenFs.readFile('./files/13.txt','utf8')
    console.log(r1,r2,r3); //111 222 333
    console.log('D');
}
getAllFile();
console.log('C');

四、EventLoop

        防止某个耗时任务导致程序假死的问题

        Js主线程从任务队列中读取异步任务的回调函数,放到执行栈中依次执行,这个过程是循环不断的,所以整个这种运行机制叫做EventLoop(事件循环)


同步任务

    非耗时任务,在主线程上排队执行的那些任务

    只有前一个任务执行完毕,才能执行后一个任务

异步任务

     耗时任务,异步任务由js委托给宿主环境进行执行

     当异步任务执行完成后,通知js主线程执行异步任务的回调函数

同步任务和异步任务的执行过程

        ①同步任务由JavaScript主线程次序执行

        ②异步任务委托给宿主环境执行

        ③已完成的异步任务对应的回调函数,会被加入到任务队列中等待执行

        ④JavaScript主线程的执行栈被清空后,会读取任务队列中的回调函数,次序执行

        ⑤JavaScript主线程不断重复上面第四步

import thenFs from 'then-fs';
console.log('A');
thenFs.readFile('./files/1.txt','utf8').then(dataStr=>{
    console.log('B');
})
setTimeout(()=>{
    console.log('C');
},0)
console.log('D');
//输出 A D C B

异步任务分类:

    ①宏任务

         异步的Ajax请求

         setTimeout、setInterval

          文件操作

          其他宏任务

  ②微任务

         Promise.then、.catch和.finally

         process.nextTick

         其他微任务

宏任务和微任务的执行顺序:

        每一个宏任务执行完毕,都会检查是否存在待执行的微任务

        如果有,则执行完所有微任务之后,再继续执行下一个宏任务

setTimeout(function(){  //宏任务
    console.log('1');
});
new Promise(function(resolve){  //同步任务
    console.log('2');
    resolve()
}).then(function(){   //微任务
    console.log('3');
});
console.log('4');  //同步任务
//输出2 4 3 1

console.log('1');  //同步
setTimeout(function(){
    console.log('2');
    new Promise(function(resolve){
        console.log('3');
        resolve();
    }).then(function(){
        console.log('4');
    })
})
new Promise(function(resolve){  //同步
    console.log('5')
    resolve();
}).then(function(){
    console.log('6');
})
setTimeout(function(){
    console.log('7');
    new Promise(function(resolve){
        console.log('8');
        resolve();
    }).then(function(){
        console.log('9');
    })
})
//输出 1 5 6 2 3 4 7 8 9

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值