初學async

開始接觸async異步函數(shù)時,只是很生硬的記住了它是異步函數(shù),當遇到異步操作的時候可以用,但是每每在遇到異步的時候又不知如何用,因為我一步步地寫代碼也是可以實現(xiàn)效果呢,干嗎非得用新的不熟悉的異步函數(shù)呢?比如我遇到這樣一個需求,左側樹拖拽移動改變父級。

由于改變父級這個方法,需要傳好多拖動的文件的詳細信息,還要再請求后臺,所以這個需求需要發(fā)起兩次請求,一次獲取詳細信息,拿到結果后再發(fā)起另一個請求改變父級,最后成功后再刷新tree就可以了。

開始我是這樣寫的(現(xiàn)在看好初級的寫法啊??方法里套方法):

onDrop = (info)=>{
      console.log('拖拽結束',info);
      const dropKey = info.node.props.eventKey;
      const dragKey = info.dragNode.props.eventKey;
      let data = {
        "id": dragKey
      }
      let url = 'http.......';
      //調(diào)接口獲取拖動的文件夾的詳細信息
      axios({
        method: 'post',
        url:url,
        headers:{'Content-type': 'application/json'},
        data:data
      }).then((res)=>{
        if(res.data.code===0){
        //這里獲取到拖動的文件的詳細信息,再作為參數(shù)調(diào)另一個接口改變父級
        let data2 = {
              "id": dragKey,
              "name": res.data.data.name,
              "pid": dropKey,
              "menuDesc": res.data.data.menuDesc
            }
        let url2 = 'http........';
         //得到結果后再調(diào)取另一個接口,改變父級
        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);
        }
      });         
    }

后來偶然看到一篇文章,我們?yōu)槭裁葱枰猘sync/await ?
真的就豁然開朗了,感謝作者(??) 。
文章里說await是等候的意思,多簡單的大白話,哈哈,那我外層的axios加上await不就可以了,直到promise執(zhí)行并取到resolve才會繼續(xù)往下執(zhí)行。也就是說promise會臨時阻塞代碼繼續(xù)往下執(zhí)行,直到取到resolve里的值,那如果用了await就必須要有promise和resolve不然就沒有任何意義了。

看到這里我就恍然大悟了,哈哈,那廢話少說上代碼:
這里的代碼并不完善,進一步優(yōu)化代碼請參考再學async

//我們在這里聲明了一個變量,接住promise里resolve的數(shù)據(jù)
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);
        }
      });

后來的事就簡單啦,在調(diào)取改變父級的接口,把menuData里的數(shù)據(jù)傳進去就可以啦~

    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必須要在函數(shù)名里加上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這種獲取結果后里面再調(diào)方法的代碼,真的感覺頭皮發(fā)麻,寫完自己都懶得看了,哈哈哈。所以異步用起來,這也是進階為中高級前端的必走之路,加油??

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容