try/catch/else

Peter van der Zee ecma at qfox.nl
Thu Feb 8 23:19:09 UTC 2018


>> On Thu, Feb 8, 2018 at 10:13 AM, Claude Pache <claude.pache at gmail.com>
>> wrote:
>>>
>>> What about the following pattern (labelled block + break)?
>>>
>>> ```js
>>> processSuggestions: {
>>>     let suggestions;
>>>     try {
>>>       suggestions = await fetchSuggestions();
>>>     } catch (e) {
>>>       alert('Failed to load suggestions');
>>>       break processSuggestions;
>>>     }
>>>     showSuggestions(suggestions);
>>> }
>>> ```

I don't mean to hijack this tread. I'm mostly curious why you opt or
even suggest for that over putting it in a function and an early
return? Like;

```
function processSuggestions() {
  let suggestions
  try {
    suggestions = await fetchSuggestions();
  } catch (e) {
    return alert('Failed to load suggestions');
  }
  showSuggestions(suggestions);
}
```

This is almost identical, especially the way the example was written.
I understand the differences, I don't think they're a problem for by
far most cases where you'd want this.

That said I wouldn't mind seeing try/catch/else/finally because the
pattern(s) above still leads to awkward code in the real world.

One could bikeshed on how "else" implies the attempt ("try") to have
failed rather than succeeded. On the other hand making it
try/then/catch/finally is also going to be confusing so whatever :)

- peter


More information about the es-discuss mailing list