Last active
August 2, 2016 21:04
-
-
Save joepie91/f6a56acdae303e90e44a to your computer and use it in GitHub Desktop.
Fallback values in promise chains
This file contains 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
/* UPDATED: This example has been changed to use the new object predicates, that were | |
* introduced in Bluebird 3.0. If you are using Bluebird 2.x, you will need to use the | |
* older example below, with the predicate function. */ | |
var Promise = require("bluebird"); | |
var fs = Promise.promisifyAll(require("fs")); | |
Promise.try(function(){ | |
return fs.readFileAsync("./config.json").then(JSON.parse); | |
}).catch({code: "ENOENT"}, function(err){ | |
/* Return an empty object. */ | |
return {}; | |
}).then(function(config){ | |
/* `config` now either contains the JSON-parsed configuration file, or an empty object if no configuration file existed. */ | |
}); |
This file contains 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
/* This example is ONLY for Bluebird 2.x. When using Bluebird 3.0 or newer, you should | |
* use the updated example above instead. */ | |
var Promise = require("bluebird"); | |
var fs = Promise.promisifyAll(require("fs")); | |
var NonExistentFilePredicate = function(err) { | |
return (err.code === "ENOENT"); | |
}; | |
Promise.try(function(){ | |
return fs.readFileAsync("./config.json").then(JSON.parse); | |
}).catch(NonExistentFilePredicate, function(err){ | |
/* Return an empty object. */ | |
return {}; | |
}).then(function(config){ | |
/* `config` now either contains the JSON-parsed configuration file, or an empty object if no configuration file existed. */ | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment