天天看點

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函數會導緻依舊是異步處理

繼續閱讀