
今天关于 javascript 中安全赋值运算符 (?=) 的新提案引起了热烈讨论。我喜欢 javascript 随着时间的推移而不断改进,但这也是我最近在一些情况下遇到的问题。我应该将一个快速示例实现作为函数,对吧?
如果您还没有阅读该提案,以下是其建议:
const [error, value] ?= maybethrows();
新的 ?= 运算符相当于在 try/catch 块中调用赋值的右侧,返回一个数组。如果在赋值中抛出了某些东西,则返回数组的第一个值将是一个错误,如果没有抛出任何东西,第二个值将是赋值的结果。
常见的 try/catch 烦恼
我经常遇到在赋值和 try/catch 块周围感觉非常丑陋的代码。像这样的事情:
let errormsg;try { maybethrow();} catch (e) { errormsg = "an error message";}
要使用 const 访问 try/catch 块之外的 errormsg,或者让您必须在块之外定义它。
非异步实现
这里最简单的情况是处理非异步函数。我能够振作起来
一些测试用例和一个名为 trycatch 的函数很快就会出现:
function trycatch(fn, ...args) { try { return [undefined, fn.apply(null, args)] } catch (e) { return [e, undefined]; }}function throws() { throw new error("it threw");}// returns a sum// prints [ undefined, 2 ]console.log(trycatch(math.sqrt, 4));// returns an error// prints [ error: 'it threw', undefined ]console.log(trycatch(throws));
trycatch 使用包含在 try/catch 块中的给定参数调用该函数。如果函数内部没有抛出任何异常,它会适当地返回 [undefined, result],如果确实抛出异常,它会适当地返回 [error, undefined]。
请注意,如果您还没有准备好调用的函数,您也可以将匿名函数与 trycatch 一起使用。
console.log(trycatch(() => { throw new error("it threw");}));
处理异步函数
异步函数变得有点棘手。我最初的一个想法是写
一个完全异步的版本,可能称为 asynctrycatch,但是其中的挑战在哪里。这是完全没有意义的探索!以下是适用于异步和非异步函数的 trycatch 实现:
function trycatch(fn, ...args) { try { const result = fn.apply(null, args); if (result.then) { return new promise(resolve => { result .then(v => resolve([undefined, v])) .catch(e => resolve([e, undefined])) }); } return [undefined, result]; } catch (e) { return [e, undefined]; }}function throws() { throw new error("it threw");}async function asyncsum(first, second) { return first + second;}async function asyncthrows() { throw new error("it throws async");}// returns a sum// prints [ undefined, 2 ]console.log(trycatch(math.sqrt, 4));// returns an error// prints [ error: 'it threw', undefined ]console.log(trycatch(throws));// returns a promise resolving to value// prints [ undefined, 3 ]console.log(await trycatch(asyncsum, 1, 2));// returns a promise resolving to error// prints [ error: 'it throws async', undefined ]console.log(await trycatch(asyncthrows));
它看起来很像原始版本,但有一些基于 promise 的代码
为了更好的措施而投入。通过此实现,您可以在调用非异步函数时调用 trycatch,然后在调用异步函数时调用 wait trycatch。
让我们看看 promise 位:
if (result.then) { return new Promise(resolve => { result .then(v => resolve([undefined, v])) .catch(e => resolve([e, undefined])) }); }
if (result.then) 检查给定函数(使用 apply 调用)是否返回 promise。如果确实如此,我们需要自己返回一个 promise。
如果没有抛出任何异常,调用 result.then(v => resolve([undefined, v])) 会导致 promise 解析为给定函数返回的值。
.catch(e => resolve([e, undefined])) 有点棘手。我最初写的
它为 .catch(e =>拒绝([e, undefined])),但这会导致未捕获的错误
脱离 trycatch。我们需要在这里解决,因为我们要返回一个
数组,不会抛出错误。
最后
我经常遇到需要尝试/抓住但感觉像是
的情况显式的 try/catch 块会占用大量空间,并且对于范围分配来说很烦人。我不确定是否会使用它,但这是一次有趣的小探索。
以上就是安全分配的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1491320.html
微信扫一扫
支付宝扫一扫