Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to specify ES6 generator method in object literal in node.js?

I cannot seem to create a generator method as object literal.

Here is my working source code:

function *getRecords (data) {
    for (var i = 0; i < data.length; i++) {
        yield data[i];
    }
}
var records = getRecords(data);
for (var record of records) {
   // process my record
}

But the when I move my generator method in object literal:

var myobj = {
    *getRecords: function (data) {...}
}

I get SyntaxError: Unexpected token *

If I add quotes

var myobj = {
    '*getRecords': function (data) {...}
}

I get: SyntaxError: Unexpected strict mode reserved word

I'm runnng nodejs v0.12.2 with --harmony option, but no matter what I do, I can't seem to get it working.

like image 886
sensor Avatar asked Apr 20 '15 14:04

sensor


People also ask

Which is the correct way to declare a generator function?

The function* declaration ( function keyword followed by an asterisk) defines a generator function, which returns a Generator object.

Can we define a method for the object in JavaScript?

JavaScript methods are actions that can be performed on objects. A JavaScript method is a property containing a function definition. Methods are functions stored as object properties.

What is the correct syntax for declaring an object literal?

Declaring methods and properties using Object Literal syntax The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array.

When should we use generators in es6?

In a normal function, there is only one entry point: the invocation of the function itself. A generator allows you to pause the execution of a function and resume it later. Generators are useful when dealing with iterators and can simplify the asynchronous nature of Javascript.


1 Answers

A @thefoureye already answered, if you are using function expressions then you will have to place the * token right after the function token.

However, you can also use method definitions in object literals. Here, you'd place the * before the generator method name indeed, however as with every method definition it does not contain the colon and the function keyword:

var myobj = {
    *getRecords(data) {
        …
    }
};
like image 188
Bergi Avatar answered Oct 20 '22 01:10

Bergi