当前位置 : 主页 > 网络编程 > JavaScript >

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

来源:互联网 收集:自由互联 发布时间:2023-01-19
目录 async与await捕捉错误 正常的输出时 try catch捕捉错误 多个异步嵌套时 await-to-js 异步嵌套使用了try,代码相对不够智能 总结 async与await捕捉错误 正常的输出时 template div class="hello"/d
目录
  • async与await捕捉错误
    • 正常的输出时
    • try catch捕捉错误
    • 多个异步嵌套时
  •  await-to-js
    • 异步嵌套使用了try,代码相对不够智能
  • 总结

    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>
    

    效果:

    在这里插入图片描述

    总结

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

    上一篇:如何利用Proxy更优雅地处理异常详解
    下一篇:没有了
    网友评论