0

I've tried replacing a try catch block with lodash' _.attempt() to clean up my server code some

let target = (_.attempt(fs.statSync( "path" ) ) );

is returning an error when the try / catch equivalent is not

I've tried with the asynch version as well, if I'm using _.attempt() incorrectly it is not clear to me, suggestions?

Erik Waters
  • 177
  • 1
  • 13

1 Answers1

3

Lodash's _.attempt() expects a function to invoke as the 1st parameter, and the arguments to the function as the 2nd:

let target = _.attempt(function(path) {
  fs.statSync(path);
}, "path");

Or the shortened version suggested ing jmmygoggle's comment:

let target = _.attempt(fs.statSync, "path");

Instead of a method to invoke, you've passed the result of fs.statSync("path"), which throws an error that _.attempt() can't handle.

Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Looking back at the documentation after your explanation and it looks so obvious, thanks for explaining it so clearly! – Erik Waters Jan 14 '17 at 18:46
  • A more brief equivalent similar to the original: `let target = _.attempt(fs.statSync, "path");` – jmmygoggle Jan 05 '18 at 22:55
  • @jmmygoggle isn't it safer to use bind, i.e const target = _.attempt(fs.statSync.bind(fs) , "path") – sktguha Oct 01 '20 at 09:58
  • @sktguha Functions without `this` references may not require `bind()` and there are likely rare scenarios where it is actually undesirable so I'd only add that extra behavior/restriction if you require it. – jmmygoggle Feb 11 '21 at 01:33
  • ok that makes sense, but in future the `statSync` function may change to reference `this` right ? so it may break then. also curious what are the rare situations it is undesirable ? – sktguha Feb 11 '21 at 17:20
  • 1
    One undesirable reason to use this broadly or generically to be "safer" could be related to future changes you mentioned. If a method was altered to arrow function syntax (`=>`), using the `bind` method could be pointless and misleading for `this` context, giving a false sense of security. E.g this answer on [non-rebindable `this` in an arrow function](https://stackoverflow.com/a/33308151/1575421) – jmmygoggle Feb 11 '21 at 19:20
  • @jmmygoggle ohh wow that is really helpful. Thanks! TIL that arrow functions cannot be rebinded. I knew earlier that they can't be used as a constructor. – sktguha Jun 07 '21 at 08:38