promise

50 阅读2分钟

原生js

<button id="btn">拉取数据</button>
<h1 id="loading" style="display: none;">加载中</h1>

//1. 点击执行ajax封装函数
        btn.onclick = function() {
            // 加载动画显示
            loading.style.display = 'block';
            ajax('https://api.tf2sc.cn/ai/tfcar/car/model', {
                headers: {
                    Platformtype: 'h5',
                    a:1,
                    b:2
                }
            }).then(res => {
                console.log(res);
            }).catch(err => {
                console.log(err);
            }).finally(() => {
                loading.style.display = 'none';
            })
        }

这里使用promise封装原生js

  function ajax(url, options) {
            return new Promise((resolve, reject) => {
                var xhr = new XMLHttpRequest();
                xhr.open('get', url);
                // for in 遍历请求头
                for (const key in options.headers) {
                   xhr.setRequestHeader(key,options.headers[key]);
                }
                xhr.send();
                xhr.onreadystatechange = function() {
                    // 3.分别条件执行then||catch
                   if (xhr.status == 200 && xhr.readyState == 4) {
                        var data = JSON.parse(xhr.responseText);
                        resolve(data);//res date
                    }
                    if (xhr.status != 200 && xhr.readyState == 4){
                        reject('请求失败');//err 请求失败
                    }
                }
            })
        }

何为回调地狱 (横向发展 层层嵌套)

  fetch('/menus').then(res => res.json()).then(res => {
      console.log(res);
      fetch(`/songList/${res.list[0].id}`).then(res => res.json()).then(res1=>{
          console.log(res1);
          fetch(`/momen/${res1.list[0].id}`).then(res=>res.json()).then(res2=>{
          console.log(res);
          })
      })
   })

为何要串联

 
  function setTime(t) {
      return new Promise((resovle, reject) => {
          setTimeout(() => {
              resovle();
          }, t);
      })
  }
  
   // 用的是一个promise回调 打印在一秒之后一起执行
  // 可以一直调用.then方法   每次then执行完之后都会返回一个promise实例  上层then的返回值,会被下一层then方法接收到
        setTime(1000).then(() => {
            console.log(1);
            return 1 + 1 + 1 + 1;
        }).then((res) => {
            console.log(2, res);
            return res + 2;
        }).then((res) => {
            console.log(3, res);
        })

图片.png 使用下面方法可以完美解决

     // 用的是五个promise回调会一起执行并且打印时间间隔一秒
  // 上层返回新的promise,则下一层then指定的就是新的promise的回调
 // 第一次执行是两秒之后执行 每次执行加一秒;
// 用的是五个promise回调会一起执行并且打印时间间隔加1秒
//第一次1秒
//第一次2秒
//第一次3秒
//第一次4秒
//第一次5秒
//共15s
  setTime(2000).then(() => {
      console.log(1);
      return setTime(3000)
  }).then(() => {
      console.log(2);
      return setTime(4000)
  }).then(() => {
      console.log(3);
      return setTime(5000)
  }).then(() => {
      console.log(4);
      return setTime(6000)
  }).then(() => {
      console.log(5);
      return setTime(7000)
  })

图片.png

图片.png

图片.png

串联fetch (fetch本身就是一个promise回调)

 fetch('https://api.tf2sc.cn/api/tfcar/car/model', {headers: {Platformtype: 'h5'}}).then(res=>res.json()).then(res=>{
      console.log(res);
      return  fetch('https://api.tf2sc.cn/api/tfcar/car/price?', {headers: {Platformtype: 'h5'}}).then(res=>res.json());
 }).then(res=>{
      console.log(res);
      return  fetch('https://api.tf2sc.cn/api/tfcar/car/list?page=1&sort=', {headers: {Platformtype: 'h5'}}).then(res=>res.json());
 }).then(res=>{
      console.log(res);
 })