本文介绍了Javascript奇怪的发生器产生子函数行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个简单的项目中使用MySQL( mysql-co )和ASQ( asynquence )来获取更好地了解ES6发电机和产量函数,我被困在一个奇怪的行为上。

I'm using MySQL (mysql-co) and ASQ(asynquence) in a simple project to get a better understanding of ES6 generators and yield functions, and I'm stumped on an odd behavior.

asynquence ()为我顺序运行生成器提供了一种简单的方法。它也可以进行伪并行执行,但这不是我现在需要的。 function * x(token)的结构来自那里。 令牌 [0] 中保存连接对象。 yield token 将控件依次传递给下一个生成函数。

asynquence (https://github.com/getify/asynquence) provides an easy way for me to run generators in sequence. It can also do pseudo-parallel execution but that's not what I need for now. The structure of function *x(token) is from there. token holds a connection object at [0]. yield token passes control on to the next generator function in sequence.

function *test1(token) {
  var conn = token.messages[0];
  var values = {id:1, dev:1, description:'This is it!'};
  yield conn.query("INSERT INTO version SET ?", values);
  yield token;
}

这工作正常。上述行被插入。我不知道MySQL驱动程序允许这样一个简单的插入函数,但它是。

This works fine. The row described above gets inserted. I didn't know the MySQL driver allowed such a simple looking insert function but it does.

function *test1(token) {
  var conn = token.messages[0];
  var values = {id:1, dev:1, description:'This is it!'};
  yield subtest1(conn, values);
  yield token;
}
function *subtest1(conn, values) {
  yield conn.query("INSERT INTO version SET ?", values);
}

这不行。对于subtest1来说,实际的代码是一个模型类,所以我不想把它与控制器合并。

This doesn't work. The actual code in question for subtest1 is in a model class, so I would prefer not to have it merged in with the controller.

我已经尝试了一堆不同的

I've tried a bunch of different things around with or without yield on the subtest function.

发生了什么?

推荐答案

subtest1(conn,values)是一个生成器。 yield 创建一个生成器对象不执行其主体。也就是说,产生的生成器保持暂停,并且需要调用 next()方法来获取第一个 yield 达到。在代码示例2 中没有显式或隐式调用 next(),这就是原因 conn.query (...)不执行。

subtest1(conn, values) is a generator. yielding a generator object does not execute its body. That is, the yielded generator remains suspended, and it would require a call to the next() method for the first yield to be reached. There are no explicit or implicit calls to next() in Code Sample 2, and this is the reason conn.query(...) isn't executed.

?从链接页面:

How about yield* subtest1(conn, values)? From the linked page:

它仍然会执行子测试懒惰

另一种解决方案是将子测试转换为常规函数,并返回 conn.query(...)(假设您只需要执行一个查询):

An alternative solution is to turn subtest into a regular function and return the result of conn.query(...) (assuming you only need to perform one query):

function subtest1(conn, values) {
    return conn.query("INSERT INTO version SET ?", values);
}

这篇关于Javascript奇怪的发生器产生子函数行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 06:21