Koa: how to handle event emitter

Created on 14 May 2016  路  2Comments  路  Source: koajs/koa

HI all,
when I use torrent-stream package , code like this

var torrentStream = require('torrent-stream');

var engine = torrentStream('magnet:my-magnet-link');

engine.on('ready', function() {
    engine.files.forEach(function(file) {
        console.log('filename:', file.name);
        var stream = file.createReadStream();
        // stream is readable stream to containing the file content 
    });
});

I find the 'engine' is event emitter, and when goto 'engine.on' function , the program is skip, doesn't into the 'engine.flies.forEach' line.
And I try many co package but program just get stuck and doesn't work, so how can i do ? Thank you all

question

Most helpful comment

you should wrap the emitter in a promise with whatever logic you'd like, then yield it.

app.use(function * (next) {
  const result = yield new Promise((resolve, reject) => {
    emitter.on('error', reject)
    emitter.on('finish', () => resolve('something'))
  })

  this.body = result
})

All 2 comments

you should wrap the emitter in a promise with whatever logic you'd like, then yield it.

app.use(function * (next) {
  const result = yield new Promise((resolve, reject) => {
    emitter.on('error', reject)
    emitter.on('finish', () => resolve('something'))
  })

  this.body = result
})

@jonathanong thanks a lot

Was this page helpful?
0 / 5 - 0 ratings