简体   繁体   English

向自身抛出错误时,Node.js生成器“已在运行”

[英]Node.js Generator “already running” when throwing errors to itself

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 (eg database fetch or something). 其中setTimeout是一些异步功能(例如,数据库获取或其他功能)。 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 (eg when Sails returns an error on exec ), it is displaying Uncaught TypeError: Generator is already running . 这在浏览器中有效,但是当我在node.js v 7.9.0的Sailsjs应用程序的Mocha集成测试中运行它时,发生错误时(例如,当Sails在exec上返回错误时),而不是显示My error message ,它显示Uncaught TypeError: Generator is already running Happy case (ie when I call gen.next(something) ) works without problems. 快乐的情况(即当我打电话给gen.next(something) )工作没有问题。 What gives? 是什么赋予了?

And before trigger-happy flag people jump in: no, when I get syntax errors or other errors that are not gen.throw n, like in this question , the behaviour is correct - error message is appropriate and stack trace points to the right place. 在触发快乐的标志的人们跳进来之前:不,当我遇到语法错误或其他不是gen.throw n的错误时,就像在这个问题中一样 ,该行为是正确的-错误消息是适当的,并且堆栈跟踪指向正确的位置。

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 解决方案是根本不使用此模式,或者将异步调用包装在Promise中,例如

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. 我去了一个像co一样的自动生成器运行器,并尽可能地使用了异步功能。 Gonna migrate the app from Sails to Koa anyway, Waterline causes way more problems than it's worth. 无论如何,要将应用程序从Sails迁移到Koa,Waterline所带来的问题多于其价值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM