async

 // 原生ajax->调用后台接口(网址、提供数据操作)
      // 理解 axios 原生ajax+Promise

      let count = 0
      function ajax(method, url) {
        count++
        // 1  创建xhr对象
        const xhr = new XMLHttpRequest()
        // 2  配置 第一个 请求方法   第二个 请求路径  (接口文档)
        xhr.open(method, url)
        // 3  监听事件
        //  请求过程中,状态发生变化就触发
        xhr.onreadystatechange = function () {
          // console.log(111)
          // console.log(xhr.status) // 200 成功
          // console.log(xhr.readyState) // 4  请求回来
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              console.log(xhr.responseText) // 拿到服务器响应内容
              if (count === 2) return
              ajax('GET', 'http://127.0.0.1:5173/list')
            }
          }
        }
        // 4 发送
        xhr.send()
      }

      ajax('GET', 'http://127.0.0.1:5173/list')
      console.log('end')
  // 原生ajax->调用后台接口(网址、提供数据操作)
      // 理解 axios 原生ajax+Promise

      function ajaxPromise(url) {
        return new Promise((resolve, reject) => {
          // ajax代码
          const xhr = new XMLHttpRequest()
          xhr.open('GET', url)
          xhr.addEventListener('loadend', function () {
            if (xhr.status >= 200 && xhr.status < 300) {
              // 请求成功
              resolve(xhr.response)
            } else {
              reject(new Error('请求失败'))
            }
          })
          xhr.send()
        })
      }

      //const p = ajaxPromise()
      /* 获取所有省->获取所有市
      ajaxPromise('http://127.0.0.1:5173/list')
        .then(
          (data) => {
            console.log('success', data)
            return ajaxPromise('http://127.0.0.1:5173/list')
          },
          (err) => {
            console.log(err)
          }
        )
        .then((data) => {
          console.log('data11111', data)
          return ajaxPromise('http://127.0.0.1:5173/list')
        })
        .then((data) => {
          console.log('data2222', data)
        })
        */
      async function getData() {
        // await 代替then提取Promise成功状态的结果
        // await后面的promise实例报错,可以用try catch捕获
        try {
          const data1 = await ajaxPromise('https://127.0.0.1:5173/list')
          console.log('-------', data1)
          const data2 = await ajaxPromise('http://127.0.0.1:5173/list')
          console.log('-------', data2)
          const data3 = await ajaxPromise('http://127.0.0.1:5173/list')
          console.log('-------', data3)
        } catch (e) {
          console.dir(e)
        }
      }
      getData()

      //  async 和 await
      //  await 配合async使用  代替then

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值