25. ES6模块化规范
25.1 定义
- 每个js文件都是独立的模块
- 通过import关键字来向内导入其他模块成员
- 通过export关键字来对外共享模块成员
25.2 Node.js体验ES6模块化
- 版本为14.15.1及以上(空文件夹终端 “type”: “module”, —> 生成package.json文件)
- 在 package.json 的根节点中添加 “type”: “module” 节点(不写默认是commonJS)
- 配置结束就可以开始使用了
25.3 模块化的基本语法
ES6 的模块化主要包含如下 3 种用法:
① 默认导出【export default
{ 变量名, 函数名… }】与默认导入【import xxx from ’ ./xxxx.js '】 —node xxxx文件名运行
② 按需导出【export const 变量xxx
|| export function 函数名
】与按需导入【import{xxx, bbb as bbbTwo }from './xxx.js'
】 — 名称必须一致;可以使用多次export;导入时可以用 as 进行重命名
import info {xxx, bbb as bbbTwo } from './xxx.js'
—— info指向默认导入的部分import default
③ 直接导入并执行【import ’ ./xxx.js '】模块中的代码(只是执行被导入模块的代码,而不拿来使用)
26. Promise
26.1 回调地狱
多层回调函数的相互嵌套,就形成了回调地狱。
回调地狱的缺点:
⚫ 代码耦合性太强,牵一发而动全身,难以维护
⚫ 大量冗余的代码相互嵌套,代码的可读性变差
解决回调地狱的问题,ES6(ECMAScript 2015)中新增了 Promise
26.2 概念
① Promise 是一个构造函数
⚫ 我们可以创建 Promise 的实例 const p = new Promise()
⚫ new 出来的 Promise 实例对象,代表一个异步操作【一次性开启多个操作】
② Promise.prototype 上包含一个 .then() 方法
⚫ 每一次 new Promise() 构造函数得到的实例对象,
⚫ 都可以通过原型链的方式访问到 .then() 方法,例如 p.then()
③ .then() 方法用来预先指定成功和失败的回调函数
⚫ p.then(成功的回调函数,失败的回调函数)
⚫ p.then(result => { }, error => { })
⚫ 调用 .then() 方法时,成功的回调函数是必选的、失败的回调函数是可选的
26.3 基于 then-fs 读取文件内容
- 基于 Promise 的方式读取文件的内容,安装
then-fs
这个第三方包
import thenFs from 'then-fs'
thenFs.readFile('.文件路径', 'utf8').then(res1 => {
xxx读取成功后的函数xxx
})
-
根据上一个的返回值.then 方法返回的Promise实例,继续通过下一个 .then() 进行处理
-
通过 .then() 方法的链式调用,就解决了回调地狱的问题。
-
thenFs.readFile(‘./files/1.txt’, ‘utf8’) —— 返回的是Promise实例对象
-
thenFs.readFile(‘./files/1.txt’, ‘utf8’)
- .then(…return thenFs.readFile(‘./files/1.txt’, ‘utf8’))
- .then(,返回promise)
- .then(…return thenFs.readFile(‘./files/1.txt’, ‘utf8’))
-
import thenFs from 'then-fs' thenFs .readFile('./files/1.txt', 'utf8') .then(res1 => { console.log(res1) return thenFs.readFile('./files/2.txt', 'utf8') }) .then(res2 => { console.log(res2) return thenFs.readFile('./files/3.txt', 'utf8') }) .then(res3 => { console.log(res3) })
-
26.4 .catch
通过Promise的原型对象上的.catch方法进行错误的捕获
.catch(err => {
console.log(err)
})
放在结尾:一捕获到错误就不再执行后面的
放在错误语段的后面:捕获之后,后面正确的还是可以执行
26.5 .all & .race
.all 等待机制,等所有的异步操作全部结束后才会执行下一步的 .then 操作 —— 输出所有
.race() 方法会发起并行的 Promise 异步操作,只要任何一个异步操作完成,就立即执行下一步的.then 操作 —— 输出最快的
import thenFs from 'then-fs'
const arr = [
thenFs.readFile('./files/1.txt', 'utf8'),
thenFs.readFile('./files/2.txt', 'utf8'),
thenFs.readFile('./files/3.txt', 'utf8')
]
Promise