Created
August 21, 2014 02:20
-
-
Save mbalex99/0db8a8bf3999a8338fcf to your computer and use it in GitHub Desktop.
Manual Promise Resolution and Rejection with Bluebird and Q
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
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); | |
}); |
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
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