首頁 > 軟體

Javascript中async與await的捕捉錯誤詳解

2022-03-03 16:01:12

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>

效果:

總結

本篇文章就到這裡了,希望能夠給你帶來幫助,也希望您能夠多多關注it145.com的更多內容!       


IT145.com E-mail:sddin#qq.com