Proposal: Syntax sugar for single exit and early exit functions.

Steve Fink sphink at gmail.com
Tue Nov 18 12:48:34 PST 2014


I have wanted something similar to this. But I think of it as having
RAII in JS.

So what I would like is:

function f() {
  let x = g();
  finally { x.cleanup(); }
  let y = h();
  finally { y.cleanup(); }
  doStuff(x, y);
}

You can sort of do this with try..finally:

function f() {
  let x, y;
  try {
    x = g();
    y = h();
    doStuff(x, y);
  } finally {
    x.cleanup();
    y.cleanup();
  }
}

The difference is that my 'finally' (1) may be placed directly after the
related setup code, and (2) is lexically scoped. (Also note that my
syntax suggestion probably wouldn't work, because a finally directly
after a try..catch block is ambiguous -- or would it work, because they
have identical behavior?)

As for:

function f() {
  if (cond) {
    finally { print(1); }
  } else {
    finally { print(2); }
  }
}

I was kind of hoping that each finally{} could use a minimal surrounding
lexical scope (so here, the bodies of the 'if' consequents), so only one
of these finally{} blocks would run. But perhaps that's a new sort of
scope from what already exists? There could be tension between finally{}
and let scoping.

Also, in

for (var x of foo()) {
  finally { print(x); }
}

I would expect the finally{} block to run on every iteration.

Could something like this fly?



More information about the es-discuss mailing list