ES6模块化
ES6模块化规范 : 浏览器和服务器通用的模块化开发规范
优点:降低了沟通成本,极大的方便了各个模块之间的相互调用
特点:
1.每一个js文件都是一个独立的模块
2.导入其它模块成员使用import关键字
3.向外共享模块成员使用export关键字
怎样在nodejs中使用ES6模块?
1. 确保安装了v14.15.1 或更高版本的node.js
2. 在package.json的根节点中添加“type”:"module"节点
基本语法
默认导出 :
export default {
n1,
show
}
默认导入 :
import m1 from './01.默认导出.js'
注意点 : 默认导出只能使用唯一一次
按需导出
export let s1 = 'aaa'
按需导入
import {s1} from '模块路径'
注意点 :
① 每个模块中可以使用多次按需导出
② 按需导入的成员名称必须和按需导出的名称保持一致
③ 按需导入时,可以使用 as 关键字进行重命名
④ 按需导入可以和默认导入一起使用
直接导入和执行模块中的代码
import 模块名
Promise : 是一个构造函数,new 出来的 Promise 实例对象,代表一个异步操作
回调地狱 : 多层回调函数的相互嵌套,就形成了回调地狱
Promise.prototype 上包含一个 .then() 方法,可以通过原型链的方式,使用实例对像直接访问
.then() 方法用来预先指定成功和失败的回调函数
p.then(成功的回调函数,失败的回调函数)
调用 .then() 方法时,成功的回调函数是必选的、失败的回调函数是可选的
then()方法支持链式调用
Promise.all()
可以将放入多个Promise实例的数组作为参数,all()会等所有的异步操作全部结束后才会执行下一步的 .then操作(等待机制)
Promise.race()
只要任何一个异步操作完成,就立即执行下一步的
.then 操作(赛跑机制)
async/await
async function getAllFile() {
console.log('B')
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/3.txt', 'utf8')
console.log(r3)
console.log('D')
}
try-catch语法:
import thenFs from 'then-fs'
async function getAllFile() {
try {
// 放的是可能会出错的代码
const r1 = await thenFs.readFile('./files/1.txt', 'utf8')
console.log(r1)
const r2 = await thenFs.readFile('./files/22.txt', 'utf8')
console.log(r2)
const r3 = await thenFs.readFile('./files/3.txt', 'utf8')
console.log(r3)
} catch (error) {
// 如果有错将执行此处代码,没错此处代码不执行
console.log(error.message)
}
}
getAllFile()
宏任务:
1. setTimeout、setInterval、
2. 异步 Ajax 请求、
3.文件操作
4.其它宏任务
微任务 :
1.Promise.then、.catch 和 .finally
2. process.nextTick
3.其它微任务
每一个宏任务执行完之后,都会检查是否存在待执行的微任务,
如果有,则执行完所有微任务之后,再继续执行下一个宏任务
优先级 同步--》 微任务----》宏任务