代码之家  ›  专栏  ›  技术社区  ›  Alejandro

npm请求模块--返回值

  •  2
  • Alejandro  · 技术社区  · 10 年前

    请求文档中的一个示例显示了以下示例:

    https://www.npmjs.com/package/request#custom-http-headers

    var request = require('request');
    var options = {
      url: 'https://api.github.com/repos/request/request',
      headers: {
        'User-Agent': 'request'
      }
    };
    
    function callback(error, response, body) {
      if (!error && response.statusCode == 200) {
        var info = JSON.parse(body);
        console.log(info.stargazers_count + " Stars");
        console.log(info.forks_count + " Forks");
      }
    }
    
    request(options, callback)
    

    假设我希望变量info的值返回给我。

    我该怎么做?

    1 回复  |  直到 10 年前
        1
  •  6
  •   thameera    10 年前

    不能从异步命令传递值。Node中使用的最常见策略。js是包装需要 info 变量,并从回调调用它。

    如:

    function callback(error, response, body) {
      if (!error && response.statusCode == 200) {
        functionThatUsesInfo(info);
      }
    }
    
    推荐文章