Promise基本概念&用法

基本概念

  1. 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值