DEV Community

Discussion on: Simplify JavaScript Promises

Collapse
 
aminnairi profile image
Amin

Hi Sunny, very interesting article. Thanks!

I especially loved this one-liner:

const data = await fetch('/api').then(res => res.json());

I think you can be even more concise and completely ditch the use of the promise.then method by using this example (inspired by yours, slightly modified so it can be easily tested):

"use strict";

async function main() {
    const api = "https://jsonplaceholder.typicode.com/users";
    const users = await (await fetch(api)).json();

    console.log(users);
}

main().catch(console.error);

This is using two await keyword, but with parenthesis to control the order of the await flow.

I also added a simple catch to handle errors (even if I'm not doing interesting stuff with it, yet).

What do you think of that? Is it better or worse? Let me know!

Collapse
 
dimitris_papadimitriou profile image
dimitrispapadimitriou

What do you think about this approach
medium.com/@dimpapadim3/asynchrono...

Collapse
 
aminnairi profile image
Amin

I like it! Even if I personally think that this API could be sexier but I'm a big fan of FP and its concept (especially in Elm, Haskell or Rust).

Collapse
 
sunnysingh profile image
Sunny Singh

Definitely more concise!

I think there is something to be said about how a .then reads a bit better, but this can be argued both ways. Either example takes advantage of the language to do one thing: fetch data.

In most scenarios, you would have a helper function anyway, which is essentially what you wrote (I would just rename it to something like fetchUsers()).

Collapse
 
bushblade profile image
Will Adams

Just wanted to add in that fetch doesn't throw errors or reject so .catch won't fire there. You need to throw your own errors with fetch.

Collapse
 
aminnairi profile image
Amin

From the documentation, it is stated that

A fetch() promise only rejects when a network error is encountered

So I guess this is the case when the fetch method can throw an error.

Thread Thread
 
bushblade profile image
Will Adams • Edited

Yeah you'll want to throw your own errors if you're using fetch and want to catch any errors. Something to be aware of otherwise most of your 'errors' will end up in your .then