📜 ⬆️ ⬇️

No need to wrap everything in a promise

Original article


Imagine that we are developing a function isPi :


 function isPi(x) { return x === 3.14 } 

And then someone says: "We do not want to know where the data comes from (database, network, etc.), so let's wrap our code in Promise":



 function isPi(px) { return px.then(x => return x === 3.14 }) } 

And we will call the function like this:


 const px = grabXfromDb() isPi(px) 

- Cool, yeah? - Not


The problem is that the statement: "We wrap the code in the Promise so that the asynchronous or synchronous code does not steam" is not true. We do not code the code, but Promise is a “something” that can:



sometime in the future:


 px.then(x => //    x    ""  isPi(x) ) 

So we can remove the redundant code:


 function isPi(x) { return x === 3.14 } const px = grabXfromDb() px.then(isPi) 

You may ask: okay, the initial code is a bit redundant, what's so bad about it? The problem arises when we try to add a reverse error - it’s very easy to end up with something like:


 function isPi(px) { return px.then(x => return x === 3.14 }) .catch(fuction(e) { assert(e instanceof SomeDBError) // -       }) } 

This is bad because now our function, through errors, knows too much about the place from where we got the Promise. The correct way to rewrite this code is:


 function isPi(x) { return x === 3.14 } grabXfromDb() .catch(fuction(e) { assert(e instanceof SomeDBError) // some code here }) .then(isPi) 

A few simple rules:



')

Source: https://habr.com/ru/post/327560/


All Articles