【问题标题】:How to put different request's response in the same document with nodejs and request?如何使用nodejs和request将不同请求的响应放在同一个文档中?
【发布时间】:2016-06-22 23:14:11
【问题描述】:

您好,我想将不同请求的响应放在同一个文档中。我有这份文件:

var result = {google:"", twitter:"", facebook:""}

我想对这些网站(google.com、Facebook.com、twitter.com)进行不同的 GET 请求,并将所有结果放在对应的字段中。 我尝试使用嵌套回调,但这样我必须先进行 google 调用,然后是 twitter 等,如下所示:

Request({
        url:first_url,
      },function(err, response, body) {
        if (err) {
             request.log(err);
        }else{
           risultato.google = body;
           Request({
        url:second_url,
      },function(err, response, body) {
        if (err) {
             request.log(err);
        }else{
           risultato.facebook = body;
           Request({
        url:third_url,
      },function(err, response, body) {
        if (err) {
             request.log(err);
        }else{
           risultato.twitter = body;
           console.log(result);
        }
       });
     }
   });
  }
 });

所以我必须知道如何并行处理所有请求,当我在结果对象中拥有所有请求的响应时,我必须使用它。

【问题讨论】:

    标签: node.js http asynchronous get request


    【解决方案1】:

    您可以使用async

    var async = require('async');
    var request = require('request');
    
    async.parallel({
      google: function(cb) {
        request("https://google.com", function(err, resp, data) {
          cb(err, data)
        })
      },
      facebook: function(cb) {
        request("https://facebook.com", function(err, resp, data) {
          cb(err, data)
        })
      },
      twitter: function(cb) {
        request("https://twitter.com", function(err, resp, data) {
          cb(err, data)
        })
      },
    }, function(err, results) {
         console.log(err, results);
         //results is now equals to {google: "", facebook: "". twitter: ""}
    });
    

    【讨论】:

      【解决方案2】:

      async 的替代方法是使用 Promise API。有一个 request-promise npm 库 (https://www.npmjs.com/package/request-promise) 为每个请求返回一个 Promise。我们可以为每个 URL 发送请求,然后在 Promise 列表中调用 Promise.All:

      const request = require('request-promise');
      const urls = ['http://google.com', 'http://yelp.com'];
      
      // List of Promises that resolve the original URL and the content
      const resultPromises = urls.map(url => {
          return request(url).then(response => ({ url, response }));
      });
      
      Promise.all(resultPromises)
          .then(results => {
              // results is an array containing the URL and response for each URL
              console.log(results);
          });
      

      【讨论】:

        猜你喜欢
        • 2017-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多