Created
March 25, 2014 23:29
-
-
Save seansullivan/9773730 to your computer and use it in GitHub Desktop.
Retrieving documents w/ promises - Q.ninvoke
This file contains hidden or 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 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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output from running is: