Promise用法总结

参照来源

\color{#666}{基本应用场景:数据处理成功之后做异步操作;}
\color{#666}{基本含义:是异步编程的一种解决方案,避免回调炼狱;}
\color{#666}{注意事项:}

1.调用resolve或reject并不会终结 Promise 的参数函数的执行;

new Promise((resolve, reject) => {
  resolve(1);
  reject(2);
  console.log(2);
}).then(r => {
  console.log(r);
});
// 2  console.log(2)会在resolve/reject之后继续执行,但是reject不会在resolve之后执行;
// 1

2.在race,all,allSettled方法中,如果抛错的Promise自己有catch,状态则也是fulfilled;
3.待续...

基本用法

异步请求数据:
getCategory(){
     let temp = true;
     return new Promise((resolve,reject)=>{
        if(temp){
         resolve('成功数据')
         // 更优写法:return resolve('成功数据')
        }else {
          //抛错方式1
           reject('err信息')
          reject(new Error('err信息'))
          //抛错方式2
          throw new Error('err信息')
        }
     },
请求数据之后:
this.getCategory().then(
(res)=>{console.log(res)}
//接收错误方式1
(err)=>{console.log(err)}
)
//接收错误方式2 --建议使用此种方式,这种方式不仅能获取promise中的错误,还能获取到then方法中的;
this.getCategory()
.then()
.catch(err=>{
    console.log(err)
})
如果有多个then()的情况,前一个回调函数返回的是一个Promise对象(即有异步操作),
后一个回调函数,就会等待前一个then执行完毕,才会被调用。

.finally(() => {···})
不管 Promise 对象最后状态如何,都会执行的操作,finally本质上是then方法的特例;
finally回调不接收参数;

promise.all基本用法:都成功的时候才得到(有catch回调例外)

const p1 = new Promise((resolve, reject) => {
  resolve('hello');
}).catch(e => e);
const p2 = new Promise((resolve, reject) => {
  resolve('world');
}).catch(e => e);

Promise.all([p1, p2])
  .then(result => {
    console.log(result) //['hello','world']
  })
  .catch(e => console.log(e))
  //then接收数组的另一种方式如下:
  // .then(([r1,r2]) => {
  //   console.log(r1) //hello
  //   console.log(r2) //world
  // })

promise.race基本用法:谁先返回得到谁,如果先的那个抛错则结束

const p1 = new Promise((resolve, reject) => {
  resolve('hello');
}).catch(e => e);
const p2 = new Promise((resolve, reject) => {
  resolve('world');
}).catch(e => e);

Promise.race([p1, p2])
  .then(result => {
    console.log(result) //hello
  })
  .catch(e => console.log(e))

Promise.allSettled 基本用法:只关心操作是否结束,并且可以得到多个请求中的所有正确的请求;

const p1 = new Promise((resolve, reject) => {
  resolve('hello');
}).catch(e => e);
const p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('world');
  }, 3000)
}).catch(e => e);
const p3 = new Promise((resolve, reject) => {
  resolve('hihihi');
}).catch(e => e);

基本用法:
Promise.allSettled([p1,p2,p3])
  .then(results=>{
    console.log(results) 
    //一个对象数组,包含每个promise得到的对象,正确的是status+value,错误的是status+reason(reason.message才能得到错误信息)
  })
  项目使用方式:
  async function getSomething() {
  const results = await Promise.allSettled([p1,p2,p3]);
  console.log('所有请求都执行完之后再做点儿啥')
  // 过滤出成功的请求
  const successfulPromises = results.filter(p => p.status === 'fulfilled');

  // 过滤出失败的请求,并输出原因
  const errors = results
    .filter(p => p.status === 'rejected')
    .map(p => p.reason);
}
getSomething()

Promise.any() 基本用法:数实例有一个变成fulfilled状态,包装实例就会变成fulfilled状态;如果所有参数实例都变成rejected状态,包装实例就会变成rejected状态,不像race一个rejected则会直接中断;
注意:该方法目前是一个第三阶段的提案,还不能正式使用。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。