js連續請求併發處理,promise和async/await

本次使用,核心在於promise和async/await的使用。

上代碼:

//獲取所有門店的數據,一萬家門店情況
this.storelists(1, 10000, "", true)
//注意async 
  .then(async e => {
    let that = this;
//for循環進行所有數據處理
    for (var i = 0; i < e.length; i++) {
//業務函數調用,注意await
      await that.settime(e[i]);
    }
//提示框開啓
    this.$store.commit("gLoading", {
      isShow: false,
      title: "更新二維碼中……"
    });
  })
  .catch(e => {
    console.log(e);
//提示框關閉
    this.$store.commit("gLoading", {
      isShow: false,
      title: "更新二維碼中……"
    });
    this.$notify({
      title: "錯誤",
      message: "獲取隊列失敗,更新終止",
      type: "error"
    });
  });
//函數封裝處理
settime(row) {
//需要用promise進行封裝
  return new Promise(resolve =>
    setTimeout(() => {
//實際業務函數
      this.StoreBuildQRcode(row)
        .then(() => {
          resolve();
        })
        .catch(e => {
          this.storeQueue.push(e);
          resolve();
        });
    }, 1500)
  );
},

小夥伴主要看代碼和我的註釋。

上面代碼是我實際項目中直接貼過來的,有語法錯誤,但是無邏輯問題。下面是簡化版。可以直接運行在支持對應的語法環境下。我已經註釋處理了

//對業務函數進行封裝
function settime(row) {
  return new Promise(resolve =>
    setTimeout(() => {
      //業務函數處理,注意業務函數也要處理成同步格式,否則會造成異步阻塞
      console.log(row);
      //核心需要返回promise格式的數據,不要返回錯誤。錯誤請自行處理業務函數邏輯,否則併發停止
      resolve();
    }, 1000)
  );
}
//async/await函數語法糖處理,利用for循環模擬併發10個的情況
async function bingfa() {
  for (var i = 0; i < 10; i++) {
    //業務函數調用
    await settime(i);
  }
}
bingfa();

不知道promise函數怎麼使用的請看我的這篇博客https://blog.csdn.net/qq_32858649/article/details/87932904

裏面講解了關於promise函數的使用。

注意:不可以用arr.map(),至少我寫不來。map函數會導致依舊是異步處理

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章