“震撼!居然还有人不了解async/await错误处理的方法

async和await其实就是一种简化了的generator语法,你可以把它理解成类似yield的东西。

比如,generator会暂停函数执行直到下一个yield,而async会等待doSth函数执行完再继续执行。

而关于错误处理,你有几种方法:

  1. 用try…catch捕获同步错误,就像这样:
<code><strong>async</strong> <strong>function</strong> <strong>a</strong>() { <strong>try</strong> { <strong>await</strong> <strong>doSth1</strong>(); } <strong>catch</strong> (e) { <strong>throw</strong> e; } }</code>
  1. 用Promise的catch方法捕获异步错误,像这样:
<code><strong>async</strong> <strong>function</strong> <strong>a</strong>() { <strong>await</strong> <strong>doSth1</strong>(); } <strong>a</strong>().<strong>catch</strong>(error => { <em>// 处理错误</em> });</code>
  1. 使用await-to-js这个小巧的npm库,它支持在node环境中使用,用起来也很方便:
<code><strong>import</strong> to <strong>from</strong> 'await-to-js'; <em>// 或者</em> <strong>const</strong> to = require('await-to-js').default; <strong>const</strong> [err, res] = <strong>to</strong>(<strong>Promise</strong>);</code>

它遵循了”error first”的理念,数组的第一个值是错误,如果没有错误则返回null。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容