Promise总结

  • 创建Promise实例 const p = new Promise()
  • 创建出来的Promise实例对象,代表一个异步操作
  • Promise.prototype 上包含一个.then()方法

    • .then()方法用来预先指定成功和失败的回调函数
    • p.then(成功的回调函数,失败的回调函数)失败的回调函数可选,成功的必选
    • p.then(result=>{},error=>{})
  • 基于Promise顺序执行操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import thenFs from 'then-fs'

thenFs
.readFile('code1/files/1.txt', 'utf8')
// 捕获错误 捕获到错误,并不影响后续正常代码的运行
.catch((err) => {
console.log(err.message)
})
.then((r1) => {
console.log(r1)
// 这儿必须返回一个新Promise对象,用来做下一步的动作
return thenFs.readFile('code1/files/2.txt', 'utf8')
})
// 针对新的Promise对象进行再操作,来保证顺序执行
.then((r2) => {
console.log(r2)
return thenFs.readFile('code1/files/3.txt', 'utf8')
})
.then((r3) => {
console.log(r3)
})
  • Promise.all()会发起并行的Promise异步操作,等所有异步操作全部结束后才会执行下一步的.then操作
  • Promise.race()会发起并行的Promise异步操作,任意一个异步操作完成,就立即执行下一步的.then操作,俗称赛跑机制,一个完成即可
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import thenFs from 'then-fs'

const promiseArr = [
thenFs.readFile('code1/files/3.txt', 'utf8'),
thenFs.readFile('code1/files/2.txt', 'utf8'),
thenFs.readFile('code1/files/1.txt', 'utf8'),
]

Promise.all(promiseArr).then(([result1,result2,result3]) => {
// 333 222 111
console.log(result1,result2,result3)
})

Promise.race(promiseArr).then((result) => {
// 可能是111,可能是222,可能是333 中的任意一个
console.log(result)
})
  • 基于Promise封装函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function getFile(fpath) {
// resolve成功回调函数,reject失败回调函数
return new Promise(function (resolve, reject) {
fs.readFile(fpath, 'utf8', (err, dataStr) => {
if (err) return reject(err)
resolve(dataStr)
})
})
}

getFile('./files/11.txt')
.then((r1) => {
console.log(r1)
})
.catch((err) => console.log(err.message))
赏个🍗吧
0%