【问题标题】:Multiple HTTP async request多个 HTTP 异步请求
【发布时间】:2018-04-10 01:58:45
【问题描述】:

我尝试从不同的 HTTP 源获取数据,但我无法处理异步模式,即使使用 async...

var express = require('express');
var app = express();
var https = require("https");
var timer = require("./my_modules/timer/timer.js");
var http = require('http');
var bodyParser = require('body-parser');
var async = require('async');
var request = require('request');

//These are my source from API.
//Output is a Json file
var sources = {
  cnn: 'https://newsapi.org/v1/articles?source=cnn&sortBy?&apiKey=c6b3fe2e86d54cae8dcb10dc77d5c5fc',
  bbc: 'https://newsapi.org/v1/articles?source=cnn&sortBy?&apiKey=c6b3fe2e86d54cae8dcb10dc77d5c5fc',
  guardian: 'https://newsapi.org/v1/articles?source=cnn&sortBy?&apiKey=c6b3fe2e86d54cae8dcb10dc77d5c5fc',
  othersource: "otherurls..."
};

//I want to push the JSON object in this array
var resultArray = [];

//I setup a https GET request
var getJson = function(url) {
  https.get(url, (res) => {
    var body = '';
    res.on('data', function(chunk) {
      body += chunk;
    });

    res.on('end', function() {
      result = JSON.parse(body);

      //push isn't working...
      resultArray.push(result);
    });

  }).on('error', function(e) {
    console.log('Got an error', e);
  });
}

app.set('port', (process.env.PORT || 5000));
app.listen(
  app.get('port'), () => {
    console.log('We are live on port: ', app.get('port'));
    getJson(sources.cnn);
  });


app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());
app.use(function(req, res, next) {
  res.setHeader('Content-Type', 'text/plain');
  res.status(404).send('Page not found !');
  res.status(503).send('Page not found, error 503');
});

console.log("resultArray:" + resultArray);
//resultArray  = empty...

我应该怎么做才能将结果推送到我的数组中?
我找不到一种方法来设置一个有效的回调函数来将结果推送到数组中。

【问题讨论】:

    标签: javascript node.js http asynchronous callback


    【解决方案1】:

    既然您已经在使用request 包,您是否尝试过以下简单的方法:

    request({
        url: sources.cnn,
        json: true
    }, function(error, response, body) {
        var articles = body.articles;
    
        // or by case, depending on what you want
        // resultArray = resultArray.concat(articles);
        resultArray.push({
            cnn: articles
        });
    
        console.log(resultArray);
    });
    

    而不是编写自己的getJson 函数?

    【讨论】:

      【解决方案2】:

      谢谢罗比,你的要求更清楚了!

      我已经仔细阅读了这篇非常清晰和有帮助的文章:https://github.com/maxogden/art-of-node#callbacks

      我想我明白了:

      //main function
      function getJson(url, callback){
        request({
            url: url,
            json: true,
            callback:callback  //added this
            }, function(error, response, body) {
      
                var articles = body.articles;
                callback(articles);
            });
      }
      
      //this callback function will be passed to the main function as the 2nd parameter
      //it's possible to access "resultArray" ONLY from this function
      var result = function(e){
        resultArray.push(e);
        console.log(resultArray);
        };
      
      //url and callback are passed as parameter
      getJson(sources.cnn, result);
      

      感谢您的帮助

      【讨论】:

        猜你喜欢
        • 2023-03-06
        • 2011-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-17
        • 2021-11-07
        相关资源
        最近更新 更多