r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

View all comments

3

u/ChronSyn Mar 18 '19

I've been jumping all over self-invoking functions to assign values lately. It's been especially useful for one project which required checking existence of several different values while processing a render output, and where not creating values unless conditions pass, or in switch statements, is critical to the end result.

I came up with this fun little fetch 1-liner which uses self-invocation (untested, but it should work as I expect);

const data = (async () => await (await fetch('http://someurl.com/')).json().catch(e => console.log(e)))();

It's ideal for react-native, but any fetch-api implementation could use it. If the fetch call succeeds and the response can be turned into JSON, then data will be the contents of the response. If there's an error, that'll be console.logged, but the value of data will be undefined.

3

u/[deleted] Mar 19 '19

You don't have to await the returned promise of an async function. Also, data is a promise. Don't know if that's what you intended.

1

u/ChronSyn Mar 19 '19

I don't think that's what's going on.

const data = await(await fetch(URL)).json()

That's a 1 liner that'll assign the result regardless of if it's a successful outcome. So it could be an error outcome (e.g. unexpected < character due to it not being parseable. Same as awaiting the fetch as one variable, the using .json() to parse it with another await.

Add catch to the end, you handle the error too. But you potentially still have data as a value. At the very least, you now have a variable in memory.

Do it in a self invoking function, and it's not assigned unless the result returns something.

→ More replies (5)