I am currently working on implementing promises in JavaScript to retrieve the first available file from a list of paths (for example, ["c:\\temp\\test1.json", "c:\\temp\\test2.json"]). The goal is to identify and return the first file that exists on disk, such as c:\temp\test2.json.
function getFirstFile(paths) {
if (!paths || paths.length == 0) {
return {};
}
// sequential async search (recursive)
var filePath = paths.shift();
return fs.readFileAsync(filePath)
// found = stop searching
.then(function (content) {
return new Promise (function (resolve, reject) {
resolve(JSON.parse(content));
})
})
// continue searching further paths left in the list
.error(function (err) {
return getFirstFile(paths);
});
}
var paths2 = ["c:\\temp\\test1.json", "c:\\temp\\test2.json"];
getFirstFile(paths2)
.then( function (index) {
assert.equal(index.file, ".test2.json");
})
.error( function(err) {
assert.fail(err.toString());
});
Despite the fact that the file "C:\temp\test2.json" is indeed present, it seems like the fs.readFileAsync(filePath) function doesn't trigger the .then(function (content) {
It's almost as though there's an uncaught exception or similar issue with the promise. What do you think could be causing this?