Strawman: `Function.prototype.try` (or `Function.try`)

Jordan Harband ljharb at gmail.com
Tue Aug 22 17:21:09 UTC 2017


I think if we wanted to add a "Result" type, we might want to do that
holistically instead of having an arbitrary prototype method return an
arbitrary object literal.

It'd be really nice to have that type, but I'm not sure how easy it'd be to
make a compelling case.

On Tue, Aug 22, 2017 at 10:01 AM, Isiah Meadows <isiahmeadows at gmail.com>
wrote:

> Usually, it's most convenient to just let errors easily fall through,
> using `try`/`catch`/`finally`. But when you're writing more low-level
> error-handling code, especially where errors are never exceptional
> (like test errors in a testing framework or task errors in a
> distributed worker pool implementation), it's often easier to handle
> completions/results as if they were values, like how Lua [1] and Rust
> [2] handle it.
>
> [1]: https://www.lua.org/pil/8.4.html
> [2]: https://doc.rust-lang.org/book/second-edition/ch09-02-
> recoverable-errors-with-result.html
>
> Here's my proposal: introduce either `Function.try(func, thisArg,
> ...args)` or `Function.prototype.try(thisArg, ...args)`. It works much
> like `Function.prototype.call`, except instead of returning/throwing,
> it always returns a `{thrown, value}` pair.
>
> Polyfilling either would be easy:
>
> ```js
> Function.try = (func, thisArg, ...args) => {
>     try {
>         return {thrown: false, value: func.call(thisArg, ...args)}
>     } catch (e) {
>         return {thrown: true, value: e}
>     }
> }
>
> Function.prototype.try = function (thisArg, ...args) {
>     try {
>         return {thrown: false, value: this.call(thisArg, ...args)}
>     } catch (e) {
>         return {thrown: true, value: e}
>     }
> }
> ```
>
> Engines could make this much more performant, though, by detecting the
> function, avoiding the object allocation if immediately destructured,
> optimizing the arguments like `Function.prototype.call`, and if called
> with a lambda, inlining the whole thing into a pseudo-`try`/`catch`.
>
> -----
>
> Isiah Meadows
> me at isiahmeadows.com
>
> Looking for web consulting? Or a new website?
> Send me an email and we can get started.
> www.isiahmeadows.com
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170822/665094c2/attachment-0001.html>


More information about the es-discuss mailing list