欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

Javascript中async与await的捕捉错误详解

时间:2022-07-09 09:35:37|栏目:JavaScript代码|点击:

async与await捕捉错误

正常的输出时

<template>
  <div class="hello">
	</div>
</template>

<script>
export default {
  name: 'HelloWorld',
  created() {
    this.init()
  },
  methods: {
    init() {
      let p1 = new Promise((resolve) => {
        setTimeout(() => {
          resolve(666)
        }, 1000)
      })
      async function run() {
        let res = await p1
        console.log('res', res)
      }
      run()
      // 正常的调用时候:log输出 666
    },
  },
}
</script>

try catch捕捉错误

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <p>
      For a guide and recipes on how to configure / customize this project,<br />
      check out the
      <a href="https://cli.vuejs.org" target="_blank" rel="noopener">vue-cli documentation</a>.
    </p>
    <h3>Installed CLI Plugins</h3>
    <ul>
      <li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel" target="_blank" rel="noopener">babel</a></li>
      <li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-eslint" target="_blank" rel="noopener">eslint</a></li>
    </ul>
    <h3>Essential Links</h3>
    <ul>
      <li><a href="https://vuejs.org" target="_blank" rel="noopener">Core Docs</a></li>
      <li><a href="https://forum.vuejs.org" target="_blank" rel="noopener">Forum</a></li>
      <li><a href="https://chat.vuejs.org" target="_blank" rel="noopener">Community Chat</a></li>
      <li><a href="https://twitter.com/vuejs" target="_blank" rel="noopener">Twitter</a></li>
      <li><a href="https://news.vuejs.org" target="_blank" rel="noopener">News</a></li>
    </ul>
    <h3>Ecosystem</h3>
    <ul>
      <li><a href="https://router.vuejs.org" target="_blank" rel="noopener">vue-router</a></li>
      <li><a href="https://vuex.vuejs.org" target="_blank" rel="noopener">vuex</a></li>
      <li><a href="https://github.com/vuejs/vue-devtools#vue-devtools" target="_blank" rel="noopener">vue-devtools</a></li>
      <li><a href="https://vue-loader.vuejs.org" target="_blank" rel="noopener">vue-loader</a></li>
      <li><a href="https://github.com/vuejs/awesome-vue" target="_blank" rel="noopener">awesome-vue</a></li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String,
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      let p1 = new Promise((reject) => {
        setTimeout(() => {
          reject(new Error('错误了哦'))
        }, 1000)
      })
      async function run() {
        try {
          let res = await p1
          console.log('res', res)
        } catch (error) {
          console.log('error', error)
        }
      }
      run()
      // 报错运行 res Error: 错误了哦
    },
  },
}
</script>

多个异步嵌套时

没有try {} catch {} 捕捉错误的

<template>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String,
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      let p1 = new Promise((resolve) => {
        setTimeout(() => {
          // reject(new Error('错误了哦'))
          resolve(1)
        }, 1000)
      })
      let p2 = function (arg) {
        return new Promise((reject) => {
          setTimeout(() => {
            console.log('arg', arg)
            reject(new Error('错误了哦'))
          }, 1000)
        })
      }
      async function run() {
        const res1 = await p1
        console.log('res1', res1) // 1
        const res2 = await p2(res1)
        console.log('res2', res2) // res2 Error: 错误了哦
      }
      run()
    },
  },
}
</script>

适使用try{} catch {} 捕捉错误的

<template>
  <div>HelloWorld</div>
</template>

<script>
export default {
  name: 'HelloWorld',
  components: {},
  data() {
    return {}
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      let p1 = new Promise((resolve) => {
        setTimeout(() => {
          // reject(new Error('错误了哦'))
          resolve(1)
        }, 1000)
      })
      let p2 = function (arg) {
        return new Promise((reject) => {
          setTimeout(() => {
            console.log('arg', arg)
            reject(new Error('错误了哦'))
          }, 1000)
        })
      }
      async function run() {
        try {
          var res1 = await p1
          console.log('res1', res1)
        } catch (error) {
          return new Error('error1', error)
        }
        try {
          const res2 = await p2(res1)
          console.log('res2', res2)
        } catch (error) {
          return new Error('error2', error)
        }
      }
      run()
    },
  },
}
</script>
<style lang="scss" scoped></style>

效果

在这里插入图片描述

 await-to-js

await-to-js官网

异步嵌套使用了try,代码相对不够智能

  • 特别使用第三方的npm包 await-to-js
  • 作用:无需 try-catch 即可轻松处理错误的异步等待包装器
  • 下载:yarn add await-to-js -S
  • 使用
<template>
  <div>HelloWorld</div>
</template>

<script>
import awaitTo from 'await-to-js'
export default {
  name: 'HelloWorld',
  components: {},
  data() {
    return {}
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      let p1 = new Promise((resolve) => {
        setTimeout(() => {
          // reject(new Error('错误了哦'))
          resolve(1)
        }, 1000)
      })
      let p2 = function (arg) {
        return new Promise((reject) => {
          setTimeout(() => {
            console.log('arg', arg)
            reject(new Error('错误了哦'))
          }, 1000)
        })
      }
      async function run() {
        const [err, res1] = await awaitTo(p1)
        if (err) throw new Error('错误1')
        console.log('res1', res1)
        const [err2, res2] = await awaitTo(p2(res1))
        if (err2) throw new Error('错误2')
        console.log('res2', res2)
      }
      run()
    },
  },
}
</script>
<style lang="scss" scoped></style>

效果:

在这里插入图片描述

总结

上一篇:JavaScript设计模式之代理模式详解

栏    目:JavaScript代码

下一篇:JS IOS/iPhone的Safari浏览器不兼容Javascript中的Date()问题如何解决

本文标题:Javascript中async与await的捕捉错误详解

本文地址:http://www.codeinn.net/misctech/207251.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有