【问题标题】:node.js request module, how to pass body of requested url to the next function using stepnode.js 请求模块,如何使用 step 将请求的 url 的主体传递给下一个函数
【发布时间】:2014-01-21 20:17:02
【问题描述】:

我想下载一个 html 页面并将其正文部分转发到下一个函数。我已经使用 step 来序列化函数。我正在使用请求模块来下载页面。

    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 传递给下一个函数?

【问题讨论】:

    标签: node.js


    【解决方案1】:

    从 Step 文档中记住:

    它接受任意数量的函数作为参数,并使用在此上下文中传递的作为下一步的回调以串行顺序运行它们。

    因此,当每个步骤被​​调用时,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);
      }
    );
    

    我的补充是在“

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-22
      • 1970-01-01
      • 2012-01-13
      • 2020-10-02
      • 1970-01-01
      • 2022-01-21
      • 2012-02-08
      相关资源
      最近更新 更多