0

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:

async best practices

callback vs promise vs asyncwait

jenryb
  • 2,017
  • 12
  • 35
  • 72
  • 1
    Notice that `async`/`await` is still promises. It's just sugar for `then` calls. – Bergi Apr 29 '18 at 19:40
  • "*I was attempting to do it with Promises until I read about async*" - do you mean `async`/`await` syntax, or the `async.js` library? Notice that promise are much more modern than the asnyc lib. – Bergi Apr 29 '18 at 19:42
  • @Bergi I mean the syntax, at first I got sidetracked by the lib, but then realized it was integrated into Node itself. I just want to try to get something going with the latest syntax with async/await – jenryb Apr 29 '18 at 19:45

1 Answers1

0

As of node 8.4 I strongly suggest using native async/await. No libraries needed anymore and clean code easy to debug and follow stack traces. No more bluebird but you can still use promisses for sync functions such as fs and rimraf etc...

Bojoer
  • 898
  • 9
  • 19