Last active
November 28, 2015 16:45
-
-
Save dmail/d31e37c09e9698caec85 to your computer and use it in GitHub Desktop.
Illustration of a case where you have register then() without using catch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Promise = require('bluebird'); | |
var fs = Promise.promisifyAll(require('fs')); | |
var existingFile = 'path/to/existing/file'; | |
var unexistingFile = 'path/to/unexisting/file'; | |
var statPromise = fs.stat(existingFile); | |
function onStatResolution(stat){ | |
return fs.readFile(unexistingFile); | |
} | |
function onStatRejection(error){ | |
if( e && e.code === 'ENOENT' ){ | |
console.log(existingFile, 'not found'); | |
} | |
else{ | |
return Promise.reject(error); | |
} | |
} | |
// In this example if you link onStatResolution & onStatRejection to statPromise | |
// with then() + catch() like so | |
statPromise.then(onStatResolution).catch(onStatRejection); | |
// you will log 'path/to/existing/file not found' | |
// while it's 'path/to/unexisting/file' which is not found | |
// you have to register them using then() only | |
// -> statPromise.then(onStatResolution, onStatRejection); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Probably a better way of dealing with this scenario, rather than using the .then(success, fail) method, would be to properly structure your execution chain to isolate the steps. You're muddying the chain a little bit by having 2 asynchronous functions that can each use the same error handler, without applying that error handler to both functions themselves. The proper way to fix this to use only a .then().catch() setup would be to add a .catch() statement to the onStatResolution function, to catch an error generated by the fs.readFile() call, like so:
function onStatResolution(state) {
return fs.readFile(unexistingFile).catch(onStatRejection);
}
Now you've explicitly defined an error handler for the fs.readFile() operation, which is distictly different (the handler is the same, but the execution chains are now differentiated) from the defined error handler for the fs.stat() operation.