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?