具有名称的生成器函数

Generator function with name

我刚刚开始使用来自 ES6 的 Bluebird 的 Promise.coroutine which is a promise version of Generator functions

当我创建一个函数并将其放入变量时一切正常。喜欢:

let success = Promise.coroutine(function* (_context) {
    ...
});

exports.success = Promise.coroutine(function* (_context) {
    ...
});

但是当我尝试创建一个独立函数时。喜欢:

Promise.coroutine(function *success() {
    ...
});

它从不定义函数,我收到错误:

success is not defined

如何访问独立的生成器函数?或者更直接一点,如何创建它?

编辑:

我正在使用 validatejs,它需要异步验证的成功和错误函数:

exports.create = function (req, res) {

    var constraints = {
        ...
    }

    validate.async(req, constraints).then(Promise.coroutine(success), Promise.coroutine(error));

    function success() {    //generator
    }

    function error(e) {     //generator
    }
}

您可以定义一个生成器函数,如下所示。

function* functionName([param[, param[, ... param]]]) {
   statements..
}

请注意,符号 * 与单词 function 相关,而不是函数名称。声明函数关键字后跟一个星号定义了一个生成器函数。

Update1: 使用 Promise.coroutine 方法。在 javascript 中,函数首先是 class 公民,因此可以作为参数传递。所以,你可以用函数名替换函数表达式。

Promise.coroutine(functionName);

您的 success() 函数不必命名,因为您实际上不是在调用它,而是在调用协程 Promise。请参见下面的示例。您应该将协程分配给您尝试从中调用它的任何对象,然后为您的延迟处理(无论可能是什么)产生一个 Promise。然后,您需要调用负责返回承诺的协程。

var Promise = require("bluebird");

function Test() {

}

Test.prototype.foo = Promise.coroutine(function* success() {
  console.log("Called success")
  var i = 0;

  while (i < 3) {
    console.log("Waiting and Yield " + i++);
    yield Promise.delay(1000);
  }
  console.log("Test " + i);
});


var a = new Test();
a.foo();
console.log("Done!");

然后你会得到这个输出:

>node index.js
Called success
Waiting and Yield 0
Done!
Waiting and Yield 1
Waiting and Yield 2
Test 3