用async和await代替promise

asyncawait

特點(diǎn)

  1. 異步、非阻塞;
  2. 基于Promise實(shí)現(xiàn)的(強(qiáng)調(diào):不能用于普通的回調(diào)函數(shù));
  3. 簡(jiǎn)潔明了,異步編程新方式。

注意

await 外層一定要有 async 包裹,不可單獨(dú)使用;

為何使用

  1. 代碼簡(jiǎn)潔,不再使用 .then() 來(lái)包裹了,類(lèi)似寫(xiě)同步代碼,逐行編寫(xiě)代碼即可
  2. 如果后臺(tái)返回的 httpcode 非兩百的同時(shí)你又想處理里面的數(shù)據(jù),必須在 .catch() 中處理 JSON.parse 的錯(cuò)誤,但是如果使用 try/catchasync/await 處理起來(lái)就異常便捷
// 示例
const fetchData = async () => {
  try {
    const data = await getList();
    console.log(data);
  } catch (err) {
    console.log(err);
  }
};

如何代替

<script>
export default {
  methods: {
    // 可能以前你會(huì)這么調(diào)用
    fetchData () {
      getUserInfo().then((data) => {
        const data = data
        if (data.id) {
          getList(data.id).then((res) => {
            if (res.length > 0) {
              getOtherList().then((response) => {
                 this.list = response.list
              })
            }
          })
        }
      })
    },
    // 現(xiàn)在可以這么調(diào)用
    async fetchData () {
      const { id } = await getUserInfo();
      if (id) {
        const res = await getList();
        if (res.length > 0) {
          const { list } = await getOtherList();
          this.list = list
        }
      }
    }
  }
}
</script>

配合 try/catch 用法

    // promise寫(xiě)法
    checkDataIsSaved({cancelButtonText} = {cancelButtonText: "暫不保存"}) {
      return new Promise(async (resolve, reject) => {
        if (!equalsObj(this.oldTableData, this.tableData)) {
          this.$confirm(
            "檢測(cè)到未保存的內(nèi)容,是否在離開(kāi)頁(yè)面前保存修改?",
            "確認(rèn)信息",
            {
              distinguishCancelAndClose: true,
              confirmButtonText: "保存",
              cancelButtonText: cancelButtonText,
              type: "warning",
            },
          )
            .then(() => {
              this.ClickFn()
              resolve();
            })
            .catch((action) => {
              if (action === "cancel") {
                resolve();
              }
              if (action === "close") {
                throw new Error("取消成功!");
              }
            });
        } else {
          resolve();
        }
      });
    }
    // 現(xiàn)在寫(xiě)法
    async checkDataIsSaved({cancelButtonText} = {cancelButtonText: "暫不保存"}) {
      if (!equalsObj(this.oldTableData, this.tableData)) {
        try {
          await this.$confirm(
            "檢測(cè)到未保存的內(nèi)容,是否在離開(kāi)頁(yè)面前保存修改?",
            "確認(rèn)信息",
            {
              distinguishCancelAndClose: true,
              confirmButtonText: "保存",
              cancelButtonText: cancelButtonText,
              type: "warning",
            },
          );
        }
        catch (err) {
          if (err === "close") {
            throw new Error("取消成功!");
          }
        }
        if (data === "confirm") {
          await this.ClickFn();
        }
      }
    }

其他的替代使用

  1. 如果代碼中有使用到 .finally() 方法,try/catch 同樣也有
try {

} catch {

} finally {

}

2.如果需要使用 Promise.all() ,無(wú)須擔(dān)心,在調(diào)用方法前全部加上 await 平鋪開(kāi)了寫(xiě)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過(guò)簡(jiǎn)信或評(píng)論聯(lián)系作者。

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

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