promise和async/await的用法


promise和async都是做異步處理的, 使異步轉為同步

1.promise

它和Promise誕生的目的都是為了解決“回調地獄”,

promise使用方法:

<button @click="testBtn()">點擊</button>

  

    get(data) {
      return new Promise((resolve, reject)=>{
        if (data > 5) {
          resolve(data);
        } else {
          reject("數據都是不大於5");
        }
      });
    },

    testF(num) {
      console.log("=====", num)
    },

    // 調用
    testBtn() {
      this.get(6).then((num)=>{
        this.testF(num);
      });
       this.get(3).then((num)=>{
        this.testF(num);
      });
    }

  

2.async

async,會返回一個promise對象

  如果async函數中是return一個值,這個值就是Promise對象中resolve的值;

  如果async函數中是throw一個值,這個值就是Promise對象中reject的值。

async的使用方法:

async function imAsync(num) {
  if (num > 0) {
    return num // 這里相當於resolve(num)
  } else {
    throw num // 這里相當於reject(num)
  }
}

imAsync(1).then(function (v) {
  console.log(v); // 1
});

// 注意這里是catch
imAsync(0).catch(function (v) {
  console.log(v); // 0
})

  

3.await

await不會單獨使用,他會和async一起使用, 如果直接使用await的話會不起作用,

await會暫停當前async函數的執行,等待后面的Promise的計算結果返回以后再繼續執行當前的async函數

使用場景:

在發起請求獲取數據的時候,如果個return返回數據, 這時就需要用到await

async test(){
const currentArr = []
await this.$axios
        .get("/topsellerCategorys/", {
          marketplaceID: item.value,
          listname: "AnyDepartment"
        })
        .then(response => {
          if (response && response.data) {
                     currentArr  = response.data
            );
          }
        })
        .catch(error => {
          this.loadingShow = false;
          console.log(error);
        });
      if (this.fristCategory[0] && this.fristCategory[0].length) {
        this.selectArr = [this.fristCategory[0][0].label]; //類目默認賦值
        this.category = this.fristCategory[0][0].label; //選擇的類目命默認賦值
      }
return  currentArr      
}

  

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM