paint-brush
Unnecessary promise wrappingby@kharandziuk
254 reads

Unnecessary promise wrapping

by Max Kharandziuk
Max Kharandziuk HackerNoon profile picture

Max Kharandziuk

@kharandziuk

Sr. JavaScript Developer

April 27th, 2017
Read on Terminal Reader
Read this story in a terminal
Print this story
Read this story w/o Javascript
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Consider you are developing a math library which has a function <code class="markup--code markup--p-code">isPi</code>.

Company Mentioned

Mention Thumbnail
Facebook
featured image - Unnecessary promise wrapping
Max Kharandziuk HackerNoon profile picture
Max Kharandziuk

Max Kharandziuk

@kharandziuk

Sr. JavaScript Developer

Consider you are developing a math library which has a function isPi.

image

Now you are saying something like — We don’t want to care where do we take the data(db, network, etc). So, the function should receive a promise:

image

and now we can use the function like this:

image

cool, yep? No.

You don’t “wrapping arbitrary user code in Promise to don’t have to care if user’s code is synchronous or asynchronous”, but a promise is something which will be resolved with some data or rejected with some error at some moment

image

so, I can remove some unnecessary code

image

You can ask: ok, the initial code is redundant, but why it’s bad? The problem appears when you add some error handling. You can easily finish with the code below:

image

It’s wrong because isPi implementation has too much knowledge about the source of a promise. The proper way to rewrite this code is something like this:

image

So, two rules of thumb here are:

  1. try to handle errors as “closer” as possible to their source
  2. separate async operations from sync. Treating everything as an async operation leads to coupled code.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.

To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!

L O A D I N G
. . . comments & more!

About Author

Max Kharandziuk HackerNoon profile picture
Max Kharandziuk@kharandziuk
Sr. JavaScript Developer

TOPICS

THIS ARTICLE WAS FEATURED IN...

Permanent on Arweave
Read on Terminal Reader
Read this story in a terminal
 Terminal
Read this story w/o Javascript
Read this story w/o Javascript
 Lite
Savepearlharbor
Aryan
Habr
Sudonull
Pvsm
Geekitbase
Habr
Savepearlharbor

Mentioned in this story

companies
X REMOVE AD