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:
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!