Add attempt

This commit is contained in:
Angelos Chalaris
2018-01-28 14:44:40 +02:00
parent 90fc391fa2
commit abac9e4c78
2 changed files with 23 additions and 0 deletions

22
snippets/attempt.md Normal file
View File

@ -0,0 +1,22 @@
### attempt
Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.
Use a `try... catch` block to return either the result of the function or an appropriate error.
```js
const attempt = (fn, ...args) => {
try {
return fn(args);
} catch (e) {
return e instanceof Error ? e : new Error(e);
}
};
```
```js
var elements = attempt(function(selector) {
return document.querySelectorAll(selector);
}, '>_>');
if (elements instanceof Error) elements = []; // elements = []
```

View File

@ -2,6 +2,7 @@ anagrams:string,recursion
arrayToHtmlList:browser,array arrayToHtmlList:browser,array
ary:adapter,function ary:adapter,function
atob:node,string,utility atob:node,string,utility
attempt:function
average:math,array average:math,array
averageBy:math,array,function averageBy:math,array,function
bind:function,object bind:function,object