I usually write it like:
const data = (await fetch(url)).then(r => r.json())
But it's very easy obviously to wrap the syntax into whatever ergonomics you like.I usually write it like:
const data = (await fetch(url)).then(r => r.json())
But it's very easy obviously to wrap the syntax into whatever ergonomics you like.
You don't need all those parens:
why not?
That's very concise. Still, the double await remains weird. Why is that necessary?
The first `await` is waiting for the response-headers to arrive, so you know the status code and can decide what to do next. The second `await` is waiting for the full body to arrive (and get parsed as JSON).
It's designed that way to support doing things other than buffering the whole body; you might choose to stream it, close the connection early etc. But it comes at the cost of awkward double-awaiting for the common case (always load the whole body and then decide what happens next).
So you can say:
It isn't, the following works fine...
Understanding Promises/A (thenables) and async/await can sometimes be difficult or confusing, especially when mixing the two like above.IMU because you don't necessarily want the response body. The first promise resolves after the headers are received, the .json() promise resolves only after the full body is received (and JSON.parse'd, but that's sync anyway).
Honestly it feels like yak shaving at this point; few people would write low-level code like this very often. If you connect with one API, chances are all responses are JSON so you'd have a utility function for all requests to that API.
Code doesn't need to be concise, it needs to be clear. Especially back-end code where code size isn't as important as on the web. It's still somewhat important if you run things on a serverless platform, but it's more important then to manage your dependencies than your own LOC count.