安全分配
今天关于 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 块会占用大量空间,并且对于范围分配来说很烦人。我不确定是否会使用它,但这是一次有趣的小探索。 以上就是安全分配的详细内容,更多请关注我的其它相关文章!