I'm using bluebird promises. I'm converting fs.exists
to existsAsync
(here's how) and fs.readFile
(here's how) to promises.
existsAsync(o.inputFilePathJSON).then(function(exists) {
debug("%s exists %s", o.inputFilePathJSON, exists);
if (exists) return fs.readFile(o.inputFilePathJSON).then(JSON.parse);
return existsAsync(o.inputFilePathYML).then(function(exists) {
debug("%s exists %s", o.inputFilePathYML, exists);
if (exists) return fs.readFile(o.inputFilePathYML).then(yaml.load);
});
})
This will check if the JSON version exists, and if it doesn't check for the YML version.
I was wondering how good this code is as promise code.
In this case I'm switching to YML from JSON. I'd love to build my YML files and check if both the JSON and YML are the same. I can't do that with this code because both of the promises don't run independently.
Here's another version of the code:
var json = existsAsync(o.inputFilePathJSON).then(function(exists) {
debug("%s exists %s", o.inputFilePathJSON, exists);
if (exists) return fs.readFile(o.inputFilePathJSON).then(JSON.parse);
return false;
})
var yml = existsAsync(o.inputFilePathYML).then(function(exists) {
debug("%s exists %s", o.inputFilePathYML, exists);
if (exists) return fs.readFile(o.inputFilePathYML).then(yaml.load);
return false;
});
json.then(function(json) {
yml.then(function(yml) {
if (yml) return yml;
if (json) return json;
return false;
});
});
What about error reporting when it comes to building these small promises? Should the errors be caught separately for each, or can they be caught in the conjoined version?
My two questions are:
- How should this promise code be written?
- Where should the errors be caught?
1 Answer 1
Interesting question,
since you need to evaluate both Promises, I would use Collections. Something like this:
Promise.all([yml(),json()]).then(function( results ) {
// Return the results of yml() if truthy, or json() if truthy, or false
return results[0] || results[1] || false;
});
Other than that, for the love of readable code:
- Use newlines in your
if
statements - Use curly braces in your
if
statements - Dont stretch your code too much horizontally
I like your 2nd approach far more than the 1st approach, the 1st approach is simply head ache inducing.