当前位置:   article > 正文

ES模块化和异步编程高级_package.json使用es模块

package.json使用es模块

在node.js中体验es6模块化

1.确保安装了node.js

2.在package.json的跟节点中添加‘type’:"module"节点

基本语法默认导入导出

导出语法export default 关键字,每个模块只能使用一次export default 关键字

import from 关键字 m1 是变量名 最后跟上路径

  1. 当前文件模块为./m1.js
  2. let a = 1
  3. let b = 2
  4. export default {
  5. a
  6. }
  7. -------------------------------------分割线---------------------------------------
  8. import m1 from './m1.js'

按需导入导出

导出语法export 关键字

按需导入和默认导入一起使用时,按需导入写在 {} 内,默认导入写在外面,逗号隔开

  1. 当前文件模块为./m1.js
  2. export let a = 1
  3. let b = 2
  4. export function fn() {}
  5. -----------------------------分割线--------------------------------------
  6. import { a,fn } from './m1.js'
  7. console.log(a);
  8. console.log(fn);

按需导入导出重命名

  1. export let a = 1
  2. import { a as str} from './m1.js'
  3. console.log(str);

Promise

概念

Promise 是一个构造函数

  • 我们可以创建Promise的实例const p = new Promise()
  • new出来的Promise 实例对象,代表一个异步操作

Promise.prototype 上有一个 then() 方法 (只要是 promise 对象都可以调用 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基本使用

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

过 .then() 方法的链式调用,就解决了回调地狱的问题;示例代码如下图:

Promise.all方法

了解async和await基本使用

async 关键字是用来修饰function函数的,所以 async 写在 function 前面;一旦被 async 修饰的函数称为异步函数

await 关键字用来修饰 Promise对象的,意味着 await 后面需要跟 Promise 对象

  1. import thenFs from 'then-fs'
  2. async function getAllFile() {
  3. const r1 = await thenFs.readFile('./files/1.txt', 'utf8')
  4. console.log(r1)
  5. const r2 = await thenFs.readFile('./files/2.txt', 'utf8')
  6. console.log(r2)
  7. const r3 = await thenFs.readFile('./files/3.txt', 'utf8')
  8. console.log(r3)
  9. }
  10. getAllFile()

基于Promise封装异步读取文件

  1. 封装代码
  2. import fs from 'fs'
  3. function reFile(fpath){
  4. return new Promise(function (resolve, reject){
  5. fs.readFile(fpath,'utf8',(req,res)=>{
  6. if(req){
  7. return reject(req)
  8. }else{
  9. resolve(res)
  10. }
  11. })
  12. })
  13. }
  14. 实验代码
  15. reFile('./files/1.text')
  16. .then((r1)=>{
  17. console.log(r1);
  18. })

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号