我想下载一个html页面并将其主体部分转发到下一个功能。我已使用步骤来序列化功能。我正在使用请求模块下载页面。
var Step = require('step');
var request = require('request');
Step(
function getHtml() {
if (err) throw err;
var url = "my url here";
request(url, function (error, response, html) {
// i want to pass the html object to the next function view
});
},
function view(err, html) {
if (err) throw err;
console.log(html);
}
);
如果我这样做,request(url, this)
则它将整个页面数据(响应和html)传递给下一个函数。
如何更改上述代码,仅将html传递给下一个函数?
请记住从步骤文档:
它接受任意数量的函数作为参数,并使用在此上下文中传递的内容作为下一步的回调,以串行顺序运行它们。
因此,当每个步骤都被调用时,this
就是您对下一步的回调。但是,您正在通过request
呼叫输入回调,因此this
到那时将有所变化。因此,我们只缓存它。
var Step = require('step');
var request = require('request');
Step(
function getHtml() {
//if (err) throw err; <----- this line was causing errors
var url = "my url here"
, that = this // <----- storing reference to current this in closure
request(url, function (error, response, html) {
// i want to pass the html object to the next function view
that(error,html) // <----- magic sauce
});
},
function view(err, html) {
if (err) throw err;
console.log(html);
}
);
我的添加内容以“ <------”开头。祝您编码愉快!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句