2022-03-18——ES6学习小记,Promise

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)
 })

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值