I'm doing a practice problem to familiarize myself with Node. I set up my app, routes, and have a controller as well.
I use an outside API and pass in different ids, and (later) I want to compare the response to a given value passed to the api I'm writing. So I am iterating over an array of ids and passing them to the api call (via the path in options) to collect all the responses.
I keep getting confused by older examples and docs... for a while I was attempting to do it with Promises until I read about async.
/**
* Controller
*/
const url = 'api.outsidesite.com';
const http = require('http');
productids = [
1, 2, 3, 4, 5, 6, 7, 8, 9
];
const options = {
hostname: url,
path: '/v1/items/${productid}?format=json&apiKey=${apiKey}',
method: 'GET',
timeout: 10000
};
exports.findOne = (request, response) => {
const req = http.request(options, res => {
res.on('data', chunk => {
response.send(chunk);
});
});
req.on('error', e => {
console.error(e);
});
req.end();
};
in my router I'm calling findOne this way:
app.get('api/products/findone/:value', products.findOne);
Now I'm stuck on iterating over and inserting the ids. I've been reading up on async/await and doing the calls in series.
Was thinking about using the built in Request library but I don't know if it's really necessary.
I tried to do it based off of this stackoverflow answer on iterating over promises
const fetchProductDetails = productids => {
return productids.reduce(function(promise, product) {
return promise.then(function() {
return findOne.done(function(res) {
console.log(res);
});
});
}, Promise.resolve());
};
fetchProductDetails(productids).then(function() {
console.log('all done');
});
but then I realized that the answer was 4 years old and there's probably a better way of doing it now. Plus the call to findOne was undefined so I got a bit confused about how to reference the export.findOne function with express in the mix. Any ideas on a clean solution for iterating? Considering using async series or something like this:
getAll = () =>
async.reduce(
productids,
0,
function(memo, item, callback) {
// pointless async:
process.nextTick(products.findOne());
},
function(err, result) {
console.log(err);
}
);
but I keep implementing older solutions and don't want to go down a wrong path again if there is a simple way to do this. Thanks!
Resources: