Skip to content

Instantly share code, notes, and snippets.

@joepie91
Last active August 2, 2016 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joepie91/f6a56acdae303e90e44a to your computer and use it in GitHub Desktop.
Save joepie91/f6a56acdae303e90e44a to your computer and use it in GitHub Desktop.
Fallback values in promise chains
/* 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 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