Reputation: 35
I have this example array
[{
"car": "Toyota",
"ID": "1",
"Doors": "4",
"price": "0"
}, {
"car": "Chevrolet",
"ID": "2",
"Doors": "2",
"price": "0"
}, {
"car": "Dodge",
"ID": "3",
"Doors": "2",
"price": "0"
}]
How can I do a request for all ID
in array, and the results of all ID
s return it in the array price.
request(
'http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name='+ID,
function (e, r, body){
var req_data = JSON.parse(body);
}
)
Thank you!
Upvotes: 0
Views: 2185
Reputation: 51866
You can use any of the interface wrappers recommended by request
and Promise.all()
. For example, using native promises and following 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
})
Upvotes: 1
Reputation: 30416
You can use async.map to do this. Using your code as a starting point it might look like this (I changed the URL to a site that I know echoes 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);
});
Upvotes: 4