0

I want to create a function that runs asynchronous code sequentialy. This function takes parameters and returns a Promise that resolves with a JavaScript object. It uses the co npm package in conjuction with generators to "pause" asynchronous code execution - run code sequentialy.

I have the following code structure in index.js and I am trying to get the result from the co function to use it.

const co = require('co');
// various imports...

module.exports = function (url, param2, param3, param4) {

  
  // Check if supplied url is reachable.
  checkURL = () => {
    return done => {
      console.log(`Checking if '${url}' is reachable...`);
      if (url.startsWith("http://")) {
        http.get(url, _ => done(null, true))
          .on('error', err => { throw new Error(`Address is unreachable. Error: ${err.message}`) });
      } else if (url.startsWith("https://")) {
        https.get(url, _ => done(null, true))
          .on('error', err => { throw new Error(`Address is unreachable. Error: ${err.message}`) });
      } else {
        throw new Error("Address is not in the 'http(s)://' format.");
      }
    }
  }

// various functions here ....

  sendReport = () => {
    return done => {
      jsonCreatorFun((err, res) => {
        if (err) {
          throw new Error(`Error: ${err.message}`);
        } else {
          done(res, true);
        }
      });
    }
  }

  // Using generators to 'sequentially' execute script
  // as things are asynchronous here.
  return co(function* () {
    var rep;
    try {
      yield checkURL();
      yield fun1();
      yield fun2();
      if (condition1) {
        yield fun3();
      }
      if (condition2) {
        yield fun4();
      }
      rep = yield sendReport();
    } catch (err) {
      handleError(err);
    }
    return rep;
  });

}

But when I am running my example.js file there are no results appart from the generator's console logs.

const myFunc = require("./index")

myFunc(url, param2, param3, params).then(res => {
    console.log("Printing result!");
    console.log(JSON.stringify(res, null, 4));
    })

Is it possible to do this?

Or even better:

const res = myFunc(url, param2, param3, params);
console.log("Printing result!");
console.log(JSON.stringify(res, null, 4));

0 Answers0