首页  >  文章  >  web前端  >  安全分配

安全分配

WBOY
WBOY原创
2024-09-10 14:30:15364浏览

Safe Assignment

今天,关于 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 =>reject([e, undefined])),但这会导致未捕获的错误
脱离 tryCatch。我们需要在这里解决,因为我们要返回一个
数组,不会抛出错误。

最后

我经常遇到需要尝试/抓住但感觉像是
的情况 显式的 try/catch 块会占用大量空间,并且对于范围分配来说很烦人。我不确定是否会使用它,但这是一次有趣的小探索。

以上是安全分配的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn