0

I yleld a Promises in co.wrap, but it throw TypeError: undefined is not a function (the error line is yield pm2.connect();)

app.js:

var app = koa();
app.init = co.wrap(function *(overwriteDB) {

  yield pm2.connect();

    koaConfig(app);

    app.server = app.listen(config.app.port);
      if (config.app.env !== 'test') {
        console.log('PM2 monitor listening on port ' + config.app.port);
      }
    });
  }

  if (!module.parent) {
    app.init().catch(function (err) {
      console.error(err.stack);
      process.exit(1);
    });
  }

In pm2.js, I wrapped a fuction to return a Promise, the code is below:

var _ = PM2.prototype;

exports = module.exports = PM2;

function PM2() {
  debug("PM2");
  if (!(this instanceof PM2)) return new PM2;
  this.env = process.env.NODE_ENV || 'development';
};

_.connect = function() {
  debug('connect');
  return new Promise(function(resolve, reject) {
    pm2.connect(function(err) {
    if (err) reject(err);
    resolve();
  });
});

Then I try

co(function *() {
  yield pm2.connect();
  var res = yield pm2.list();
  console.log(res);
});

in app.js, it works OK.

zwb
  • 679
  • 1
  • 6
  • 16
  • What is `pm2`, where are you getting it from? Are those two `pm2`s you're using different objects? The one of them does not seem to return promises – Bergi Aug 19 '15 at 23:09
  • @Bergi, the two pm2s are the same Object **function PM2**, I push my code to: https://github.com/zwb-ict/pm2-monitor . You can checkout to test. Thank you. – zwb Aug 20 '15 at 02:04
  • You shouldn't be exporting a constructor from your pm2 module, but a singleton object with some promise-returning methods that match the original pm2. If it were me I wouldn't even bother creating a pm2 wrapper; just use something like this https://www.npmjs.com/package/ugly-adapter – greim Aug 20 '15 at 03:18
  • Thank you @greim, I found I didn't get Object PM2(), I changed to require('./lib/pm2')(); I works OK. I'll try ugly-adapter – zwb Aug 20 '15 at 03:56
  • JavaScript is case sensitive in variable names. – Benjamin Gruenbaum Aug 20 '15 at 10:10

1 Answers1

0

I forgot ()

require('./lib/pm2')(); 
zwb
  • 679
  • 1
  • 6
  • 16