初学async

作者: 那头黑马 | 来源:发表于2019-08-15 11:38 被阅读0次

开始接触async异步函数时,只是很生硬的记住了它是异步函数,当遇到异步操作的时候可以用,但是每每在遇到异步的时候又不知如何用,因为我一步步地写代码也是可以实现效果呢,干吗非得用新的不熟悉的异步函数呢?比如我遇到这样一个需求,左侧树拖拽移动改变父级。

由于改变父级这个方法,需要传好多拖动的文件的详细信息,还要再请求后台,所以这个需求需要发起两次请求,一次获取详细信息,拿到结果后再发起另一个请求改变父级,最后成功后再刷新tree就可以了。

开始我是这样写的(现在看好初级的写法啊😅方法里套方法):

onDrop = (info)=>{
      console.log('拖拽结束',info);
      const dropKey = info.node.props.eventKey;
      const dragKey = info.dragNode.props.eventKey;
      let data = {
        "id": dragKey
      }
      let url = 'http.......';
      //调接口获取拖动的文件夹的详细信息
      axios({
        method: 'post',
        url:url,
        headers:{'Content-type': 'application/json'},
        data:data
      }).then((res)=>{
        if(res.data.code===0){
        //这里获取到拖动的文件的详细信息,再作为参数调另一个接口改变父级
        let data2 = {
              "id": dragKey,
              "name": res.data.data.name,
              "pid": dropKey,
              "menuDesc": res.data.data.menuDesc
            }
        let url2 = 'http........';
         //得到结果后再调取另一个接口,改变父级
        axios({
              method: 'post',
              url:url2,
              headers:{'Content-type': 'application/json'},
              data:data2
              }).then((res)=>{
              if(res.data.code===0){
                //移动成功后刷新左侧tree即可
                this.refreshLeftTree();
              }else{
                message.error(res.data.message);
              }
            }); 
         })
        }else{
          message.error(res.data.message);
        }
      });         
    }

后来偶然看到一篇文章,我们为什么需要async/await ?
真的就豁然开朗了,感谢作者(🌹) 。
文章里说await是等候的意思,多简单的大白话,哈哈,那我外层的axios加上await不就可以了,直到promise执行并取到resolve才会继续往下执行。也就是说promise会临时阻塞代码继续往下执行,直到取到resolve里的值,那如果用了await就必须要有promise和resolve不然就没有任何意义了。

看到这里我就恍然大悟了,哈哈,那废话少说上代码:
这里的代码并不完善,进一步优化代码请参考再学async

//我们在这里声明了一个变量,接住promise里resolve的数据
let menuData = await axios({
        method: 'post',
        url:url,
        headers:{'Content-type': 'application/json'},
        data:data
      }).then((res)=>{
        if(res.data.code===0){
          return new Promise((reslove, reject) => {
              reslove(res.data.data);
         })
        }else{
          message.error(res.data.message);
        }
      });

后来的事就简单啦,在调取改变父级的接口,把menuData里的数据传进去就可以啦~

    let data2 = {
              "id": dragKey,
              "name": menuData.name,
              "pid": dropKey,
              "menuDesc": menuData.menuDesc
            }
      let url2 = 'http.......';
      axios({
              method: 'post',
              url:url2,
              headers:{'Content-type': 'application/json'},
              data:data2
            }).then((res)=>{
              if(res.data.code===0){
                this.refreshLeftTree();
              }else{
                message.error(res.data.message);
              }
        }); 

当然如果要用await必须要在函数名里加上async,像这样:

  onDrop = async (info)=>{...}

如果我们把两个axios分别都封装好两个方法,那最终结果看起来是这样的:

// 获取详情
getDetailData(dropKey, dragKey){
    axios({
      method:'post',
      ...
    }).then((res)=>{
        return  new Promise((reslove, reject) => { reslove(res) })
}
//改变父级
changeParent(data){
  axios({
      method:'post',
      ...
    }).then((res)=>{ this.refreshTree() }
} 
onDrop = async (info) {
    const dropKey = info.node.props.eventKey;
    const dragKey = info.dragNode.props.eventKey;
    const data = await this.getDetailData(dropKey, dragKey);
    this.changeParent(data);
}

小结
这就是所谓的,虽然异步但是代码看起来是同步的写法,顿时增加了易读性,易于维护有木有,反正本人在看到像axios这种获取结果后里面再调方法的代码,真的感觉头皮发麻,写完自己都懒得看了,哈哈哈。所以异步用起来,这也是进阶为中高级前端的必走之路,加油💪

相关文章

  • 初学async

    开始接触async异步函数时,只是很生硬的记住了它是异步函数,当遇到异步操作的时候可以用,但是每每在遇到异步的时候...

  • async

    async/await特点 async/await更加语义化,async是“异步”的简写,async functi...

  • ES7 - async

    async 基本使用 async 传递参数 async 错误处理

  • async和await

    浅谈Async/Await用 async/await 来处理异步 async和await async:声明一个异步...

  • promise async settimeout setImme

    // setTimeout async promise执行顺序总结async function async1() ...

  • async和await的使用

    async函数 什么是async函数? async函数是使用async关键字声明的函数。 mdn文档:https:...

  • nodejs async 使用简介

    async await node async 使用

  • async函数

    async 要理解 async 先要掌握 Promise 的概念,了解 Promise 请戳我! async 函数...

  • ES7 Async/Await快速入门

    用法: 使用async 声明函数,在async函数内使用await async function xxx(){aw...

  • 055 Python语法之异步IO-Async

    Async初识 异步下载 异步下载Async

网友评论

    本文标题:初学async

    本文链接:https://www.haomeiwen.com/subject/mtvajctx.html