-1

I am new in Q. lib

When do we need to use Q.defer ?

what is the benefit?

can we return promise with q.defer?

 var deferred = Q.defer();
FS.readFile("foo.txt", "utf-8", function (error, text) {
if (error) {
    deferred.reject(new Error(error));
} else {
    deferred.resolve(text);
}
 });
  return deferred.promise;
JLRishe
  • 99,490
  • 19
  • 131
  • 169
user1365697
  • 5,819
  • 15
  • 60
  • 96
  • 1
    What part of the documentation don't you understand? – SLaks Jan 04 '15 at 18:37
  • Possible duplicate of [**How do I convert an existing callback API to promises**](http://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises). – Benjamin Gruenbaum Jan 04 '15 at 21:11

1 Answers1

4

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!");
});
JLRishe
  • 99,490
  • 19
  • 131
  • 169