Promise

① Promise 是一个构造函数
⚫ 我们可以创建 Promise 的实例 const p = new Promise()
⚫ new 出来的 Promise 实例对象,代表一个异步操作
② Promise.prototype 上包含一个 .then() 方法
⚫ 每一次 new Promise() 构造函数得到的实例对象,
⚫ 都可以通过原型链的方式访问到 .then() 方法,例如 p.then()
③ .then() 方法用来预先指定成功和失败的回调函数
⚫ p.then(成功的回调函数,失败的回调函数)
⚫ p.then(result => { }, error => { })
⚫ 调用 .then() 方法时,成功的回调函数是必选的、失败的回调函数是可选的

 

Promise.all() 方法会发起并行的 Promise 异步操作,等所有的异步操作全部结束后才会执行下一步的 .then
操作(等待机制)

const promiseArr = [
    thenfs.readFile('./txt/1.txt','utf8'),
    thenfs.readFile('./txt/2.txt','utf8'),
    thenfs.readFile('./txt/3.txt','utf8')
]
Promise.all(promiseArr).then((res)=>{
    console.log(res)   //[ '111', '222', '333' ]
})
 

Promise.race() 方法会发起并行的 Promise 异步操作,只要任何一个异步操作完成,就立即执行下一步的
.then 操作(赛跑机制)

 

 

posted @ 2022-03-05 23:18  FinnYY  阅读(20)  评论(0编辑  收藏  举报