Promise基本概念&用法
基本概念
- Promise是一个构造函数
1、我们可以创建promise的实例
const p = new Promise()
new 处理的Promise实例对象,代表一个异步操作
2、Promise.prototype上包含一个.then()方法
每一次通过new Promise() 构造函数得到的实例对象
都可以通过原型链条的方式访问到.then()方法 例如p.then()
3、.then()方法用来预先指定成功失败的回调函数
p.then(成功的回调函数,失败的回调函数)
p.then(result=>{},error=>{})
调用.then()方法时,成功回调函数是必选的,失败回调函数是可选的
基于回调函数按顺序读取文件内容
then-fs基本使用
安装 npm i then-fs
示例
import thenFs from 'then-fs'
thenFs.readFile('./files/1.txt','utf8').then((r1)=>{console.log(r1)})
thenFs.readFile('./files/2.txt','utf8').then((r2)=>{console.log(r2)})
thenFs.readFile('./files/3.txt','utf8').then((r3)=>{console.log(r3)})
基于promise顺序读取文件内容
import thenFs from "then-fs";
thenFs.readFile('./files/1.txt','utf8').then(r1=>{
console.log(r1)
return thenFs.readFile('./files/2.txt','utf8')
}).then(r2=>{
console.log(r2)
return thenFs.readFile('./files/3.txt','utf8')
}).then((r3)=>{
console.log(r3)
})
promise通过.catch方法捕获异常
import thenFs from "then-fs";
thenFs.readFile('./files/1.txt','utf8').then(r1=>{
console.log(r)
return thenFs.readFile('./files/2.txt','utf8')
}).then(r2=>{
console.log(r2)
return thenFs.readFile('./files/3.txt','utf8')
}).then((r3)=>{
console.log(r3)
}).catch(err=>{
console.log(err.message)
})
# 输出 r is not defined
promise.all()方法
定义:promise.all()方法 会发起并行的promise异步操作 ,等所有的异步操作全部结束后才会执行下一步的.then操作(等待机制)
import thenFs from "then-fs";
const promiseArr=[
thenFs.readFile('./files/1.txt','utf8'),
thenFs.readFile('./files/2.txt','utf8'),
thenFs.readFile('./files/3.txt','utf8')
]
Promise.all(promiseArr).then(result=>{
console.log(result)
})
# 打印 [ '111', '222', '333' ]
promise.rase()方法
定义:promise.rase()方法 会发起并行的promise异步操作,只要任何一个异步操作完成,就执行下一步的.then()操作(赛跑机制)
import thenFs from "then-fs";
const promiseArr=[
thenFs.readFile('./files/1.txt','utf8'),
thenFs.readFile('./files/2.txt','utf8'),
thenFs.readFile('./files/3.txt','utf8')
]
Promise.race(promiseArr).then(result=>{
console.log(result)
})
# 打印 222