Promise基础使用

Promise是ES6引入的异步编程的新解决方案,语法上Promise是一个构造函数,用来封装异步操作并可以获取其成功或者失败的结果。

基本语法

  

 Promise.prototype.then

 调用then方法,then方法的返回结果是Promise对象,对象状态由回调函数的执行结果决定

  • 如果回调函数中返回的结果是非Promise类型的属性,状态为成功,返回值为对象的成功的值
  •  如果回调函数中返回的结果是Promise类型,则返回值为该Promise的返回值

 

   

 catch使用

在上面的例子中,then后面有两个函数,用户成功或失败的回调。如果在知道是错误的回调时,除了上面这样在第二个函数里面操作外,还可以直接使用catch语法:

 axios中的Promise

链式调用

在实际项目中,我们会对接口进行封装,被封装的接口已经是一个Promise,可以直接进行链式调用

promiseListOne()
    .then((one) => {
      console.log('one', one)
      return promiseListTwo().then((res) => {
        return res
      })
    })
    .then((res) => {
      console.log('链式返回', res)
    })
    .catch((res) => {
      console.log('链式报错', res)
    })

 

 当链式调用接口报错时,通过catch可以捕捉报错

promiseListOne()
    .then((one) => {
      console.log('one', one)
      return promiseListTwo().then((res) => {
        return res
      })
    })
    .then((two) => {
      console.log('two', two)
      return promiseListThree().then((res) => {
        return res
      })
    })
    .then((three) => {
      console.log('three', three)
      return promiseListFour().then((res) => {
        console.log('第4个接口', res)
        return res
      })
    })
    .then((res) => {
      console.log('链式返回', res)
    })
    .catch((res) => {
      console.log('链式报错', res)
    })

 

 promise.all

当某个页面需要等待多个请求全部返回时,可以使用promise.all

const getListOne = async () => {
  const res = await promiseListOne()
  console.log(res)
  return res
}
const getListTwo = async () => {
  const res = await promiseListTwo()
  console.log(res)
  return res
}
onMounted(() => {
  let promiseArr = [getListOne(), getListTwo()]
  Promise.all(promiseArr).then((value) => {
    console.log('全部请求完成', value)
  })
})

const getListTwo = async () => {
  const res = await promiseListTwo()
  console.log(res)
  return res
}
onMounted(() => {
  let promiseArr = [1, 2, 3].map(() => {
    return getListTwo()
  })
  Promise.all(promiseArr).then((value) => {
    console.log('全部请求完成', value)
  })
})

 

posted on 2020-12-06 11:40  紅葉  阅读(89)  评论(0编辑  收藏  举报