对于来自数组Node.js的每个请求

时间:2017-07-18 17:21:51

标签: javascript arrays node.js for-loop asynchronous

我有这个示例数组

[{
  "car": "Toyota",
  "ID": "1",
  "Doors": "4",
  "price": "0"
}, {
  "car": "Chevrolet",
  "ID": "2",
  "Doors": "2",
  "price": "0"
}, {
  "car": "Dodge",
  "ID": "3",
  "Doors": "2",
  "price": "0"
}]

如何对数组中的所有ID发出请求,并且所有ID的结果都会以数组价格返回。

request(
  'http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name='+ID,
  function (e, r, body){
    var req_data = JSON.parse(body);
  }
)

谢谢!

2 个答案:

答案 0 :(得分:4)

您可以使用async.map执行此操作。使用您的代码作为起点它可能看起来像这样(我将URL更改为我知道与JSON相呼应的网站):

var request = require('request');
var async = require('async');
var data = [{
              "car": "Toyota",
              "ID": "1",
              "Doors": "4",
              "price": "0"
            }, {
              "car": "Chevrolet",
              "ID": "2",
              "Doors": "2",
              "price": "0"
            }, {
              "car": "Dodge",
              "ID": "3",
              "Doors": "2",
              "price": "0"
            }];

async.map(data , function(item, callback) {
  request("https://randomvictory.com/random.json?id="+item.ID,
           function(error, response, body) {
             if(!error) {
               //having checked there was no error, you pass 
               //the result of `JSON.parse(body)` as the second
               //callback argument so async.map can collect the
               //results
               callback(null, JSON.parse(body));
             }
           });
}, function(err, results) {
  //results is an array of all of the completed requests (note
  //that the order may be different than when you kicked off
  //the async.map function)
  console.log(err, results);
});

答案 1 :(得分:1)

您可以使用any of the interface wrappers recommended by requestPromise.all()。例如,使用native promises并跟随this example

const request = require('request-promise-native')

Promise.all(array.map(({ ID }) => request({
  uri: `http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=${ID}`,
  json: true
})).then(data => {
  // each of the response objects in the same order as initial array
  data.forEach(objRes => console.log(objRes))
}).catch(error => {
  // handle the first rejected error here
})