Search code examples
javascriptnode.jsecmascript-6bluebird

Generator function with name


I have just started using Bluebird's Promise.coroutine which is a promise version of Generator functions from ES6.

Everything works fine when I create a function and put it in a variable. Like:

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

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

But when I try to create an standalone function. Like:

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

It never defines a function and I get the error:

success is not defined

How do I access an standalone generator function? or more straight forward, how to create it?

Edit:

I am using validatejs, it requires success and error functions for async validations:

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
    }
}

Solution

  • You can define a generator function as shown below.

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

    Please note that symbol * is with word function and not the functionname. The declaration function keyword followed by an asterisk defines a generator function.

    Update1: Usage with the Promise.coroutine method. In javascript, function are first class citizen and hence can be passed as an parameter. So, you can replace the function expression with the functionname.

    Promise.coroutine(functionName);