How do I get the value of the text from the example below?
Q.js has an example on using Deferred:
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;
In this case, there is a node async function being used. What I want to do is get the value of text from the deferred.promise being returned. When I console.log(deferred.promise) I get this:
{ promiseSend: [Function], valueOf: [Function] }
What am I doing wrong (as I just copy/pasted the example from here: https://github.com/kriskowal/q#using-deferreds) or what else do I need to do to actually get that text from the file?
I am aware that node.js has a synchronous version of the call above - my goal is to understand how deferred works with this library.
$q. defer() allows you to create a promise object which you might want to return to the function that called your login function.
The defer attribute is a boolean attribute. If the defer attribute is set, it specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing.
If you are creating a Deferred, keep a reference to the Deferred so that it can be resolved or rejected at some point. Return only the Promise object via deferred. promise() so other code can register callbacks or inspect the current state. For more information, see the documentation for Deferred object.
The deferred. promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request.
See https://github.com/kriskowal/q#adapting-node
Can be rewritten in a nodejs-like:
var read = Q.nfcall(FS.readFile, FS, "foo.txt", "utf-8");
read().then( function (text) { console.log(text) } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With