paint-brush
Unnecessary promise wrappingby@kharandziuk
254 reads

Unnecessary promise wrapping

by Max KharandziukApril 27th, 2017
Read on Terminal Reader
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
featured image - Unnecessary promise wrapping
Max Kharandziuk HackerNoon profile picture

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

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:

and now we can use the function like this:

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

so, I can remove some unnecessary code

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:

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:

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!