Skip to content

Instantly share code, notes, and snippets.

@mbalex99
Created August 21, 2014 02:20
Show Gist options
  • Save mbalex99/0db8a8bf3999a8338fcf to your computer and use it in GitHub Desktop.
Save mbalex99/0db8a8bf3999a8338fcf to your computer and use it in GitHub Desktop.
Manual Promise Resolution and Rejection with Bluebird and Q
var Promise = require('bluebird');
var fetchPostById = function(postId){
return new Promise(function(resolve, reject){
mySampleAsyncDatabaseFetch(postId, function(err, post){
if(err){
reject(err);
}
resolve(post);
});
});
};
//later you can do
fetchPostById(1234).then(function(post){
console.log("Found post 1234");
console.log(post);
}).catch(function(err){
console.log("Wow something seriously went wrong!");
console.log(err);
});
var Q = require('Q');
var fetchPostById = function(postId){
var deferred = Q.defer();
mySampleAsyncDatabaseFetch(postId, function(err, post){
if(err){
deferred.reject(err);
}
deferred.resolve(post);
});
return deferred.promise;
};
//later you can do
fetchPostById(1234).then(function(post){
console.log("Found post 1234");
console.log(post);
}, function(err){
console.log("Wow something seriously went wrong!");
console.log(err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment