javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > Javascript中async与await的捕捉错误

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

作者:小渣亮

这篇文章主要为大家详细介绍了Javascript中async与await的捕捉错误,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

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,代码相对不够智能

<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>

效果:

在这里插入图片描述

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!       

您可能感兴趣的文章:
阅读全文