Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Q.js - Using deferred

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.

like image 678
Chris Abrams Avatar asked Sep 20 '12 03:09

Chris Abrams


People also ask

What is Q defer ()?

$q. defer() allows you to create a promise object which you might want to return to the function that called your login function.

How do I use JavaScript Deferred?

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.

How use jQuery Deferred and promise?

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.

What is Deferred promise in JavaScript?

The deferred. promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request.


1 Answers

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) } );
like image 52
vaughan Avatar answered Oct 02 '22 19:10

vaughan