Skip to content

Instantly share code, notes, and snippets.

@seansullivan
Created March 25, 2014 23:29
Show Gist options
  • Save seansullivan/9773730 to your computer and use it in GitHub Desktop.
Save seansullivan/9773730 to your computer and use it in GitHub Desktop.
Retrieving documents w/ promises - Q.ninvoke
var Q = require('q');
var documents = {
'a': "Document A",
'b': "Document B",
'c': "Document C"
};
/**
* get a document by key
*
* Simulates Mongoose Model method
* @param {String} key in document
* @callback {Function}
* @return {void}
*/
var model = function () {};
model.prototype.getDocument = function (key, done) {
setTimeout(function () {
if(documents[key]) {
return done(null, documents[key]);
}
done(new Error('Invalid document'));
}, 0);
};
var getDocumentWrapper = function (key) {
var modelInstance = new model();
return Q.ninvoke(modelInstance, 'getDocument', key);
};
getDocumentWrapper('a')
.then(function (result) {
console.log(result);
return getDocumentWrapper('d');
})
.fail(function (err) {
console.log('Error thrown =(');
console.error(err);
});
@seansullivan
Copy link
Author

Output from running is:

Document A
Error thrown =(
[Error: Invalid document]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment