Promise
Promise概念
是一个构造函数
- 我们可以创建Promise实例 const p =new Promise()
- new 出来的Promise实例对象,代表一个异步操作
Promise.prototype 上包含一个.then()方法
- 每一次 new Promose() 构造函数得到的实例对象
- 都可通过原型链的方式访问到.then()方法例如p.then()
.thern()方法用来预先指定成功和失败的回调函数
- p.then(成功的回调函数,失败的回调函数)
- p.then(tesult=>{},error=>{})
3.1 then-fs 方法
调用then-fs 提供的readFile()方法,可以异步的读取文件内容,它的返回值是Promise的对象。因此可以调用.then()方法为每个Promise异步操作指定成功和失败之后的回调函数。实例代码如下
import thenFs from "then-fs";
thenFs.readFile('./data/a.txt','utf-8').then((ra)=>{
console.log(ra)
})
thenFs.readFile('./data/b.txt','utf-8').then((rb)=>{
console.log(rb)
})
异步按顺序读取文件内容
import thenFs from "then-fs";
thenFs.readFile('./data/a.txt','utf-8').then((r1)=>{
console.log(r1)
return thenFs.readFile('./data/b.txt','utf-8')
})
.then((r2)=>{
console.log(r2)
return thenFs.readFile('./data/c.txt','utf-8')
})
.then((r3)=>{
console.log(r3)
})
Promise.all()方法:所有方法执行结束才会会立即执行下一步的.then()操作(等待机制)
import thenFs from "then-fs";
const PromiseArr=[
thenFs.readFile('./data/a.txt','utf-8') ,
thenFs.readFile('./data/b.txt','utf-8') ,
thenFs.readFile('./data/c.txt','utf-8')
]
Promise.all(PromiseArr).then(result=>{
console.log(result)
})
PS C:\Users\O20110005\Desktop\ES6> node 09.Promise.All.js
[ 'aaa', 'bbb', 'ccc' ]
Promise.race()方法:只要任何一个方法执行结束就会立即执行下一步的.then()操作 (赛跑机制)
import thenFs from "then-fs";
const PromiseArr=[
thenFs.readFile('./data/a.txt','utf-8') ,
thenFs.readFile('./data/b.txt','utf-8') ,
thenFs.readFile('./data/c.txt','utf-8')
]
Promise.reac(PromiseArr).then(result=>{
console.log(result)
})