用async和await代替promise

asyncawait

特点

  1. 异步、非阻塞;
  2. 基于Promise实现的(强调:不能用于普通的回调函数);
  3. 简洁明了,异步编程新方式。

注意

await 外层一定要有 async 包裹,不可单独使用;

为何使用

  1. 代码简洁,不再使用 .then() 来包裹了,类似写同步代码,逐行编写代码即可
  2. 如果后台返回的 httpcode 非两百的同时你又想处理里面的数据,必须在 .catch() 中处理 JSON.parse 的错误,但是如果使用 try/catchasync/await 处理起来就异常便捷
// 示例
const fetchData = async () => {
  try {
    const data = await getList();
    console.log(data);
  } catch (err) {
    console.log(err);
  }
};

如何代替

<script>
export default {
  methods: {
    // 可能以前你会这么调用
    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
              })
            }
          })
        }
      })
    },
    // 现在可以这么调用
    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写法
    checkDataIsSaved({cancelButtonText} = {cancelButtonText: "暂不保存"}) {
      return new Promise(async (resolve, reject) => {
        if (!equalsObj(this.oldTableData, this.tableData)) {
          this.$confirm(
            "检测到未保存的内容,是否在离开页面前保存修改?",
            "确认信息",
            {
              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();
        }
      });
    }
    // 现在写法
    async checkDataIsSaved({cancelButtonText} = {cancelButtonText: "暂不保存"}) {
      if (!equalsObj(this.oldTableData, this.tableData)) {
        try {
          await this.$confirm(
            "检测到未保存的内容,是否在离开页面前保存修改?",
            "确认信息",
            {
              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() ,无须担心,在调用方法前全部加上 await 平铺开了写

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

相关阅读更多精彩内容

友情链接更多精彩内容