2

I wander if it's possible to use arrow function with generators like this:

app.use( *() => {
    ...body of function
});

Thanks!

Carnaru Valentin
  • 1,690
  • 17
  • 27
  • 2
    Did you try running it ? – Serge K. Jul 21 '17 at 07:58
  • Ok, you're ironic... and how should syntax looks like? – Carnaru Valentin Jul 21 '17 at 08:09
  • Yes I am, you're basically asking if you can run the code you wrote, go ahead, try it yourself and see what happens ! Then, when you'll see it doesn't work, either do your own searches, or look at @hsz 's answer. – Serge K. Jul 21 '17 at 08:14
  • 1
    If needed, you can easily omit generator function name to achieve anonymous function, like `app.use(function*() { /* body of generator */ })`. More discuss here: https://stackoverflow.com/a/34108006/7878274 – Vladislav Ihost Jul 21 '17 at 08:15
  • Yes, but for arrows function maybe works like `*() => {}" or "()* => {}` and so on.. You see? It's difference to be smart and think you're smart... – Carnaru Valentin Jul 21 '17 at 08:16

2 Answers2

3

No, it's not possible to make it shorter than described in the documentation:

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

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*

Kaiido
  • 123,334
  • 13
  • 219
  • 285
hsz
  • 148,279
  • 62
  • 259
  • 315
0

You can, but not really in a nice way. It's not shorter and does not look that pretty. Check this out:

function* iterable(arg) {
    yield* [];
}

async function* asyncIterable(arg) {
    yield* [];
}

const arrowIterable = arg => {
    return {
        *[Symbol.iterator]() {
            yield* [];
        },
    };
};

const arrowAsyncIterable = arg => {
    return {
        async *[Symbol.asyncIterator]() {
            yield* [];
        },
    };
};

This works because an iterable is basically an object with the Symbol.iterator or Symbol.asyncIterator set to an iterator. A generator is an iterator!

Enjoy!

Elmer
  • 9,147
  • 2
  • 48
  • 38