什么是“功能*()”在nodejs中意味着什么? [英] What does "function*()" mean in nodejs?

查看:107
本文介绍了什么是“功能*()”在nodejs中意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这个页面看到了这个偶像: function *(){...} https://github.com/jmar777/suspend 并不确定它的作用。

I came across this idom: function* (){ ... } from this page https://github.com/jmar777/suspend and not sure what does it do.

有人可以解释一下吗?
谢谢!

Could anyone explain? Thanks!

推荐答案

这意味着该函数是一个生成器函数。引自 http://wiki.ecmascript.org/doku.php?id = harmony:generators#syntax

It means that the function is a generator function. Quoting from http://wiki.ecmascript.org/doku.php?id=harmony:generators#syntax


带*标记的函数称为生成函数。

A function with a * token is known as a generator function.

正常函数执行并返回结果。但是生成器会产生值并等待它们再次被调用。然后该函数恢复执行。

Normal functions execute and return the result. But generators yield values and wait for them to get invoked again. Then the function will resume its execution.

通常迭代生成器函数。因为,它们产生值并从下一个函数调用等待继续执行,它们对于无限值生成器很有用。

Generator functions are normally iterated over. Since, they yield the values and wait from the next function call to resume execution, they are useful for infinite values generators.

它们是内存效率也很高。例如,假设您要生成10000000个数字,如果我们将它们存储在数组中,我们可能会耗尽机器的内存。但是如果我们使用一个生成器,我们可以生成一个数字,屈服值,当再次调用时,将恢复执行,并且可以生成下一个数字。

They are memory efficient as well. For example, lets say you want to generate 10000000 numbers, if we store them in an Array, we might exhaust the machine's memory. But if we use a generator, we can generate one number, yield value and when called again execution will be resumed and the next number can be generated.

我们可以看看示例,此处

function* fibonacci() {
    let [prev, curr] = [0, 1];
    for (;;) {    // Infinite looping
        [prev, curr] = [curr, prev + curr];
        yield curr;
    }
}

正如我所说,生成器像这样迭代

And as I said, generators are iterated like this

for (n of fibonacci()) {
    // truncate the sequence at 1000
    if (n > 1000)
        break;
    print(n);
}

看到生成器函数实际上有一个无限循环。当 yield curr 执行时,值将返回到 n in n of fibonacci() 。这在迭代中使用,当再次调用生成器时,它恢复执行(它也将数据保留在变量中)并生成下一个元素。

See the generator function actually has an infinite loop. When yield curr is executed, value will be returned to n in n of fibonacci(). That is used in the iteration and when the generator is called again, it resumes the execution (it retains the data in variables as well) and generates the next element.

这篇关于什么是“功能*()”在nodejs中意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆