0

I am using the following pattern in my code:

let gen = (function*(){
    let foo = yield setTimout((err, something)=> err ? gen.throw(err) : gen.next(something), 1000, new Error('My error message'), null);
    console.log(foo);
})();
gen.next();

Where setTimeout is some async function (e.g. database fetch or something). This works inside browser, but when I run it inside a mocha integration test for my Sailsjs app from node.js v 7.9.0, instead of displaying My error message, when the error occurs (e.g. when Sails returns an error on exec), it is displaying Uncaught TypeError: Generator is already running. Happy case (i.e. when I call gen.next(something)) works without problems. What gives?

And before trigger-happy flag people jump in: no, when I get syntax errors or other errors that are not gen.thrown, like in this question, the behaviour is correct - error message is appropriate and stack trace points to the right place.

Megakoresh
  • 746
  • 1
  • 11
  • 30
  • It appears that when I return a promise and call `gen.throw` from the promise `then` or `catch`, everything works fine. This only happens in generic callbacks. – Megakoresh Jun 19 '17 at 13:33

1 Answers1

0

This seems to be related to the callback triggering multiple times on error if the debugger is be believed. The solution is either not to use this pattern at all, or wrap the async call in a Promise like so

let foo = yield new Promise((res, rej)=>setTimout((err, something)=> err ?
 rej(err) : 
 res(something),
 1000, 
 new Error('My error message'), 
 null))
   .then(something=>gen.next(something)
   .catch(err=>gen.throw(err));

Ugly, isn't it? I went for a co-like automatic generator runner, and async functions where I could. Gonna migrate the app from Sails to Koa anyway, Waterline causes way more problems than it's worth.

Megakoresh
  • 746
  • 1
  • 11
  • 30