ES6中Promise使用

378 阅读1分钟

描述

  • Promise对象接收两个参数一个是resolve、一个是reject。Promise是构造函数。
  • resolve是一个函数,将Promise对象的状态从pending变为resolved,返回异步操作的结果作为参数传递出去。
  • reject是一个函数,将Promise对象的状态从pending变为rejected,将错误作为参数传递出去。
  • Promise实例生成后then方法可以指定resolved状态和rejected状态的回调函数,第二个函数是可选的,不一定要提供。
promise.then(function(value) {
  // resolve success
}, function(error) {
  // reject failure
});

hello world示例

  • Promise新建后就会立即执行,then方法所有同步任务执行完才会执行
  • then方法返回的还是一个新的Promise实例,因此可以 p.then().then()……
  • 一般来说,不要在then方法中定义reject的回调函数,用catch方法比较好
// bad
promise
  .then(function(data) {
    // success
  }, function(err) {
    // error
  });

// good
promise
  .then(function(data) { //cb
    // success
  })
  .catch(function(err) {
    // error
  });

注意

  • await 要 配合 async 使用
  • async 返回的是 promise
  • Promise.then 返回的也是 promise‘
  • Promise.all 用于多个处理多个异步对象

多个异步请求时的处理

1、处理两个异步请求哇 这是用promise all的一种方法
  // 这是用promise all的一种方法
  initFormConfig() {
    let res1 = []
    let res2 = []
    const p1 = request({
      url: '',
      methods: 'get',
      params
    })
    const p2 = request({
      url: '',
      method: 'post',
      params
    })

    Promise.all([p1, p2]).then((res) => {
      res1 = res[0]
      res2 = res[1]
    })
  }

2、处理两个异步请求哇 这是用async await的方法处理的一种方法
  // 要处理两个异步请求哇 这是用async await的方法处理的一种方法
  initFormConfig = async () => {
     try {
       const res1 = await request({
         url: '',
         methods: 'get',
         params: {},
       })

      const res2 = await request({
         url: '',
         method: 'get',
         params: {},
       })
        
    } catch (err) {
      console.log(err)
    }
 }

或者

initFormConfig = async () => {
    await request({
      url: '',
      methods: 'get',
      params: {},
    }).then((res) => {
      res1 = res
    })

    await request({
      url: '',
      method: 'get',
      params: {},
    }).then((res) => {
      res2 = res
    })
}