One of the main authors of the Q library has written an article stating that Q.defer()
is unnatural and outdated (although it does still have some practical applications).
The more modern approach (which is what the article is about) is the revealing constructor pattern. This is also the approach that is in the ES6 Promise standard (defer
is not included in the standard), so you are best off using that when it is available:
return Q.Promise(function (resolve, reject) {
FS.readFile("foo.txt", "utf-8", function (error, text) {
if (error) {
reject(new Error(error));
} else {
resolve(text);
}
});
});
But to get to (what I think is) the gist of your question, both Q.defer()
and the above pattern are useful when you want to create a promise from an Async API that does not produce promises. If you use promises in your code, it's a good idea to use promises for all of your async code rather than mixing and matching. The Q.Promise()
constructor and Q.defer()
allow you to bridge that gap.
Note: Since you are working with a Node-style API, there is a simpler technique designed specifically for this. You can use Q.nfbind
to convert a node-style async function into a function that returns promises:
var readFile = Q.nfbind(FS.readFile);
readFile("foo.txt", "utf-8").then(function (data) {
console.log("Got the file!");
});