Saturday 23 November 2019

javascript - Should promises be avoided in synchronous functions?

I am currently trying to beautify some NodeJS legacy code and doing so came up with this questions where I could not find any best-practice or go-to-guide (if you know any, please share it with me).



The aim is to not simply see that one can combine synchronous and asynchronous code via Promises (this is clear), but why one should e.g. go for synchronous code if the synchronous processing of a function is clear. This means what disadvantages would it have to simply add a Promise to the synchronous code? Are there any? E.g. in the runtime or, more important, in the asynchronous process flow?



E.g. take the following example for an async function:



Foo.prototype.addNode = function addNode() {
var self = this;
return new Promise(function (resolve, reject) {

var node = new Node(self.getNodes().getLastId() + 1);
resolve (self.getNodes().add(node));
});
}


In our business logic this function should indeed be async, since this is called recursively in a promise chain.



However, the function add is handled synchronously, since this is a simple Array.push() of a generic element with some validation.




GenericElementList.prototype.add = function add(T) {
if (this.T.length === 0) {
this.T.push(T);
this.typeOfT = T.constructor;
return this;
}
else {
if (!(T.constructor === this.typeOfT)){
this.T.push(T);
return this;

}
else {
throw new IllegalArgumentError('Invalid type of element to push into array! Was: ' + T.constructor.name + ' but should be: ' + this.typeOfT.name + '!');
}
}
};


(So to avoid confusion: self.getNodes() returns an element Node which is a GenericElement and the GenericElementList is a list data structure for GenericElements.)




Now my question is: Would there be any disadvantages regarding runtime or process flow in the asynchronous processing of these methods, if we would add a Promise to the add-function? Are there any reasons to avoid that? Or would the only disadvantage be some boilerplate code?

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...