workshopper / learnyounode

Learn You The Node.js For Much Win! An intro to Node.js via a set of self-guided workshops.
Other
7.24k stars 1.84k forks source link

Understanding Exercise 9 problem! #706

Closed tpkahlon closed 4 years ago

tpkahlon commented 4 years ago

I got stuck at Exercise 9, went through lot of online solutions and suggestions. Some use BL package, some don't work. In conclusion, neither of these break down problem to understand how things are working. I tried to use async package suggested by team but it works if I pass all URLs properly. However, if you pass null or empty string, it breaks on my end. It does not pass testing as well.

const async = require("async");
const fetch = require("node-fetch");
const urls = process.argv.slice(2);

const cb = async (url) => {
  if (!url.includes("http")) {
    return {
      message: "URL is not valid",
    };
  }
  const response = await fetch(new URL(url));
  const text = await response.text();
  return text;
};

async.map(urls, cb, (err, results) => {
  if (err) throw err;
  return results.forEach((result) => {
    if (result.message) return console.log(result.message);
    return console.log(result);
  });
});

Testing the case in terminal:

// Works: node juggling-async http://www.google.com http://www.reddit.com
// Does not work: node juggling-async http://www.google.com http://www.reddit.com null

Any advice will be appreciated!

UPDATE: I have resolved it, not sure if approach is right.