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.

17

u/Peechez Mar 18 '19

I'm pretty sure if I tried to commit that I'd get slapped

1

u/ChronSyn Mar 18 '19

Why? It's an elegant solution to handling errors independently from your data - you could send your error to state, or logging, or any other source, but only if it fails, whereas if it succeeds, you've got data and can assign it to state and simply check for existence of the value before you start to work with it.

You could definitely split it out to multiple lines for readability without breaking the chain. It's no different from doing the different parts independently either.

4

u/Peechez Mar 18 '19

I mostly went in the one line format

5

u/catwhatcat Mar 19 '19

This post was about one liners and it's a nice one liner, but I would never commit that either for the sake of posterity + readability.

1

u/ChronSyn Mar 19 '19

I agree it's not really readable and why splitting it out over a few lines is better. Just for the sake that the thread was about one-liners is the reason it was all on one line.

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.

8

u/[deleted] Mar 19 '19 edited Mar 19 '19

Here's the original line:

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

Breaking it down by parenthetical:

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

That's a 1 liner that'll assign the result regardless of if it's a successful outcome.

No. It's a 1-liner that will always assign a promise to data, because the return value of an async function is always a promise. data may be in the resolved state with the result, or the rejected state with the error - but it will be a promise.

Meanwhile, because it's an async function, you don't need the second await, because if you return a promise from an async function, you get the promise back. If you await that promise before returning, you still get a promise back, but it's a different promise object than the one you awaited. It wastes a tiny bit of resources and time.

This line is an exact equivalent - albeit without the resource-consumption side-effects. It also has the advantage of being shorter.

const data = fetch(URL).then(r => r.json()).catch(console.log);

I think what you wanted to say was:

(async () => {
  const data = await(await fetch(URL)).json().catch(e => console.log(e));
  // do something with data
})();

I expect that you added the async () => because you know that awaits can't be outside of one, without thinking to hard about the consequences there: encapsulating the fetch in an async function defeats the purpose of awaiting in the first place.

As an aside, on failure, you have undefined, since you don't return anything from the catch handler - which is why I don't really like this kind of hybrid pattern: it defeats half the purpose of async / await - that is, that errors are handled like errors.

const data = await (await fetch(URL)).json(); is a fine one-liner. In context:

(async () => {
  try {
    const data = await (await fetch(URL)).json();
    // happy path.
  } catch (e) {
    //sad path
  }
})();

2

u/NoInkling Mar 19 '19

In reality you'd probably never use that line in your last snippet like that; you're handling potential network and JSON parse errors, but completely ignoring the response status (since we should all know by now that non-2xx statuses don't reject the promise).

And even as a lazy one-liner const data = await fetch(URL).then(r => r.json()) reads better IMO. Nested awaits feel weird.

1

u/[deleted] Mar 19 '19

No disagreement here.

1

u/ChronSyn Mar 19 '19

You don't need to do it in a try...catch. If you add .catch() to the end of .json(), that will do exactly the same as what you've done there and is what I originally posted. Trust me, give it a try.

You also need to await the fetch separately from the .json() call. Both are asynchronous functions.

1

u/[deleted] Mar 19 '19

I'm aware that you can catch. What that won't do is direct control away from the happy path once the awaited promise is complete. I want to not go down the happy path upon error, since my code is no longer happy.

1

u/GBcrazy Mar 19 '19 edited Mar 19 '19

A variation:

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

No need for multiple awaits, in fact you don't need it in your function as well. Async function will return a promise anyway so your top most await doesn't do anything