问题
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.
回答1:
You can get the value via the .then() method of a Promise:
function read() {
// your snippet here...
}
read().then(function (text) {
console.log(text);
});
Also, error handlers can be passed either as a 2nd argument to .then()
or with the .fail()
method:
read().fail(function (err) {
console.log(err);
});
回答2:
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) } );
回答3:
Q = require('q');
FS = require('fs');
function qread() {
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;
};
var foo = qread();
setTimeout(function() {
console.log(""+foo);
},1000);
It's strange you cannot see the output for console.log(foo)
. Dont' know why.
Check more examples here https://github.com/kriskowal/q/wiki/Examples-Gallery
回答4:
deferred.promise.then(function (text) {
console.log(text); // Bingo!
});
回答5:
Q = require('q');
FS = require('fs');
var deferred = Q.defer();
FS.readFile("client-02.html", "utf-8", function (error, text) {
if (error) {
deferred.reject(new Error(error));
} else {
deferred.resolve(text);
}
return deferred.promise.done( setTimeout(console.log(text),1000 ));
});
来源:https://stackoverflow.com/questions/12505850/q-js-using-deferred