I have this function which uses promises and is working correctly:
parse: function (fileAsString, options) {
return when.promise(function(resolve, reject){
if (fileAsString.length) {
var metaData = options || {};
var points = extractPointsFromPCD(fileAsString);
var cleanedPoints = cleanPoints(points);
var cordsAndRGBs = createCoordinateAndRGBObjects(cleanedPoints);
var res = removeExtremePoints(3, cordsAndRGBs);
var pcdContainer = {
coordinateAndRGBObjs: res.points,
average: res.average,
metaData: metaData,
fileString: fileAsString
};
// TODO: do meaningful test
if(res && res.points && res.average && metaData && fileAsString){
resolve(pcdContainer);
} else {
// TODO: add actual error
reject("something went wrong");
}
} else {
console.log(LOG + "No file!");
}
});
}
As you can see, every function return the value that I need to use in the nextfunction. But I also need to aggregate the various return values because these are the ones the parse function should reuturn. removeExtermePoints even return an object!
I was well on the way to refactor the parse function so that also the subFunctions use promises when I was unsure how to go on. The code I had looked basically like this:
parse: function (fileAsString, options) {
return when.promise(function(resolve, reject){
if (fileAsString.length) {
var metaData = options || {};
extractPointsFromPCD(fileAsString)
.then(cleanPoints)
.then(createCoordinateAndRGBObjects)
.then(removeExtremePoints)
.done(function(pcdContainer){
resolve(pcdContainer);
});
} else {
reject(LOG + "No file to parse!");
}
});
}
Question 1
I don't have any references to the single return values anymore. I assume I could just use an object that I pass into the first promise, keep pushing it through all the following, adding the values and return that, but I'm not sure if that is a good way of getting to what I had in mind in the first snippet?
Question 2
removeExtremePoints
takes a factor as input and I want to stay that way. I assume I can use resolve(3, result)
in createCoordinateAndRGBObjects
? I really don't like this, because all of a sudden the function createCoordinateAndRGBObjects
determines how I want to run removeExtremePoints
, I'd rather define the parameter in the parse body.
Also, what if at some point I change something, maybe the promise after createCoordinateAndRGBObjects
is not removeExtremepoints
for another use case. How would I go about it?