Promise的使用

Promise的使用

问题:多层回调函数 相互嵌套 就形成了回调地狱

缺点: 大量冗余代码相互嵌套可读性很差 不易维护

setTimeout(()=>{
    setTimeout(()=>{
        setTimeout(()=>{
            
        },3000)
    },2000)
},1000)
如何解决回调地狱

Es6 新增了promise的概念

1:Promise是一个构造函数

​ 创建一个promise实例,const p = new Promise()

​ new出来的promise实例对象,代表一个异步操作

2:Promise.prototype上包含一个then方法

​ 每次new Promise得到的实例对象

​ 都可以通过原型链的方式访问到then方法

3:then方法用来预先指定成功和失败的回调函数

4:catch方法用来捕获错误的

var p = new Promise()
p.then(成功的回调函数,失败的回调函数)
p.then(()=>{},()=>{})

**注意:**调用then方法,成功的回调函数是必选的,失败的回调函数是可选的

Promise 构造函数 参数是一个回调函数,回调函数有两个参数resolve reject
new出来的promise实例对象,代表一个异步操作
异步请求成功执行resolve方法 异步请求失败执行reject方法
promise状态: 等待 pending 成功 fulfilled 失败rejected 状态一旦改变,不能再更改

 new Promise((resolve, reject) => {
      console.log($)
      //  异步请求
      $.ajax({
        type: 'GET',
        url: 'http://www.liulongbin.top:3006/api/getbooks',
        success(res) {
          // resolve(res)
          reject('错误')
        },
      })
    })
      .then((res) => {
        console.log(res, 'res')
        return res.data
      })
      .then((res1) => {
        console.log(res1, 'res1')
        return 4
      })
      .then((res2) => {
        console.log(res2)
      })
      .catch((err) => {
        //专门用来捕获错误的
        console.log(err, 'catch')
      })
all方法

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

 // http://www.liulongbin.top:3006/api/news
    // Promise.all()方法会发起**并行**的Promise异步操作,
    // 等所有的异步操作全部结束后才会执行下一步的then操作
    function fn() {
      return axios({
        method: 'GET',
        url: 'http://www.liulongbin.top:3006/api/news',
      })
    }

    function fn1() {
      return axios({
        method: 'GET',
        url: 'http://www.liulongbin.top:3006/api/getbooks',
      })
    }

    Promise.all([fn(), fn1()])
      .then(([res1, res2]) => {
        console.log(res1, res2)
      })
      .catch((err) => {
        console.log(err)
      })
race方法

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

 // Promise.race()方法会发起**并行**的Promise异步操作,只要任何一个异步操作完成,就立即执行下一步的then操作
    function fn() {
      return axios({
        method: 'GET',
        url: 'http://www.liulongbin.top:3006/api/news',
      })
    }

    function fn1() {
      return axios({
        method: 'GET',
        url: 'http://www.liulongbin.top:3006/api/getbooks',
      })
    }

    Promise.race([fn(), fn1()])
      .then((res) => {
        // 只要任何一个异步操作完成,就立即执行下一步的then操作
        console.log(res)
      })
      .catch((err) => {
        console.log(err)
      })
基于promise封装异步请求

1:定义方法getPromise

2:方法接收参数请求的数据,请求的url

3:方法的返回值未promise实例对象

  function getBookList(data, url) {
      return new Promise((resolve, reject) => {
      //异步请求
        axios({
          method: 'GET',
          url: url,
          params: data,
        })
          .then((res) => {
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    }

    getBookList({}, 'http://www.liulongbin.top:3006/api/getbooks')
      .then((res) => {
        console.log(res)
      })
      .catch((err) => {
        console.log(err)
      })

async/await

async/await 是es6引入的新语法,用来简化promise异步操作,在async/await出现之前,我们只能通过then的方法处理promise异步操作

如果在function中使用了await 那么function必须被async修饰

在async方法中,第一个await之前的代码会同步执行,await之后的代码会异步执行

  function fn() {
      return axios({
        method: 'GET',
        url: 'http://www.liulongbin.top:3006/api/news',
      })
    }

    function fn1() {
      return axios({
        method: 'GET',
        url: 'http://www.liulongbin.top:3006/api/getbooks',
      })
    }
    // async 说明函数是一个异步操作的函数
    // 按照顺序执行异步请求数据
    async function getData() {
      console.log(2)
      // await等待
      let res1 = await fn1()
      console.log(res1)
      let res2 = await fn()
      console.log(res2)
      console.log(1)
    }

    getData()
    // async -await  用同步的写法 执行异步操作
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值