node.js - Chaining promises -
what want accomplish parsing given website , writing title titles.txt
. using request module fetching website , cheerio getting title.
i using q module creating next 2 promises:
readtitle
var readtitle = function(url) { var deferred = q.defer(); request({ url: url }, function(err, response, body) { var $ = cheerio.load(body); deferred.resolve($("title").text()); }); homecoming deferred.promise; };
writetitle
var writetitle = function(title) { var deferred = q.defer(); fs.appendfile('titles.txt', title + "\n", function() { deferred.resolve(); }); homecoming deferred.promise; };
i expect next script write google
, stack overflow
text file:
readtitle('http://www.google.com') .then(writetitle) .then(readtitle('http://www.stackoverflow.com')) .then(writetitle);
but is:
google undefined
what doing wrong?
then
needs passed function rather value
.then(function() {return readtitle('http://www.stackoverflow.com'); }) .then(writetitle);
node.js promise q
No comments:
Post a Comment